Edit on GitHub

Expressions

Every AST node in SQLGlot is represented by a subclass of Expression.

This module contains the implementation of all supported Expression types. Additionally, it exposes a number of helper functions, which are mainly used to programmatically build SQL expressions, such as sqlglot.expressions.select.


   1"""
   2## Expressions
   3
   4Every AST node in SQLGlot is represented by a subclass of `Expression`.
   5
   6This module contains the implementation of all supported `Expression` types. Additionally,
   7it exposes a number of helper functions, which are mainly used to programmatically build
   8SQL expressions, such as `sqlglot.expressions.select`.
   9
  10----
  11"""
  12
  13from __future__ import annotations
  14
  15import datetime
  16import math
  17import numbers
  18import re
  19import typing as t
  20from collections import deque
  21from copy import deepcopy
  22from enum import auto
  23
  24from sqlglot._typing import E
  25from sqlglot.errors import ParseError
  26from sqlglot.helper import (
  27    AutoName,
  28    camel_to_snake_case,
  29    ensure_collection,
  30    ensure_list,
  31    seq_get,
  32    subclasses,
  33)
  34from sqlglot.tokens import Token
  35
  36if t.TYPE_CHECKING:
  37    from sqlglot.dialects.dialect import DialectType
  38
  39
  40class _Expression(type):
  41    def __new__(cls, clsname, bases, attrs):
  42        klass = super().__new__(cls, clsname, bases, attrs)
  43
  44        # When an Expression class is created, its key is automatically set to be
  45        # the lowercase version of the class' name.
  46        klass.key = clsname.lower()
  47
  48        # This is so that docstrings are not inherited in pdoc
  49        klass.__doc__ = klass.__doc__ or ""
  50
  51        return klass
  52
  53
  54class Expression(metaclass=_Expression):
  55    """
  56    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
  57    context, such as its child expressions, their names (arg keys), and whether a given child expression
  58    is optional or not.
  59
  60    Attributes:
  61        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
  62            and representing expressions as strings.
  63        arg_types: determines what arguments (child nodes) are supported by an expression. It
  64            maps arg keys to booleans that indicate whether the corresponding args are optional.
  65        parent: a reference to the parent expression (or None, in case of root expressions).
  66        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
  67            uses to refer to it.
  68        comments: a list of comments that are associated with a given expression. This is used in
  69            order to preserve comments when transpiling SQL code.
  70        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
  71            optimizer, in order to enable some transformations that require type information.
  72
  73    Example:
  74        >>> class Foo(Expression):
  75        ...     arg_types = {"this": True, "expression": False}
  76
  77        The above definition informs us that Foo is an Expression that requires an argument called
  78        "this" and may also optionally receive an argument called "expression".
  79
  80    Args:
  81        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  82    """
  83
  84    key = "expression"
  85    arg_types = {"this": True}
  86    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
  87
  88    def __init__(self, **args: t.Any):
  89        self.args: t.Dict[str, t.Any] = args
  90        self.parent: t.Optional[Expression] = None
  91        self.arg_key: t.Optional[str] = None
  92        self.comments: t.Optional[t.List[str]] = None
  93        self._type: t.Optional[DataType] = None
  94        self._meta: t.Optional[t.Dict[str, t.Any]] = None
  95        self._hash: t.Optional[int] = None
  96
  97        for arg_key, value in self.args.items():
  98            self._set_parent(arg_key, value)
  99
 100    def __eq__(self, other) -> bool:
 101        return type(self) is type(other) and hash(self) == hash(other)
 102
 103    @property
 104    def hashable_args(self) -> t.Any:
 105        args = (self.args.get(k) for k in self.arg_types)
 106
 107        return tuple(
 108            (tuple(_norm_arg(a) for a in arg) if arg else None)
 109            if type(arg) is list
 110            else (_norm_arg(arg) if arg is not None and arg is not False else None)
 111            for arg in args
 112        )
 113
 114    def __hash__(self) -> int:
 115        if self._hash is not None:
 116            return self._hash
 117
 118        return hash((self.__class__, self.hashable_args))
 119
 120    @property
 121    def this(self):
 122        """
 123        Retrieves the argument with key "this".
 124        """
 125        return self.args.get("this")
 126
 127    @property
 128    def expression(self):
 129        """
 130        Retrieves the argument with key "expression".
 131        """
 132        return self.args.get("expression")
 133
 134    @property
 135    def expressions(self):
 136        """
 137        Retrieves the argument with key "expressions".
 138        """
 139        return self.args.get("expressions") or []
 140
 141    def text(self, key) -> str:
 142        """
 143        Returns a textual representation of the argument corresponding to "key". This can only be used
 144        for args that are strings or leaf Expression instances, such as identifiers and literals.
 145        """
 146        field = self.args.get(key)
 147        if isinstance(field, str):
 148            return field
 149        if isinstance(field, (Identifier, Literal, Var)):
 150            return field.this
 151        if isinstance(field, (Star, Null)):
 152            return field.name
 153        return ""
 154
 155    @property
 156    def is_string(self) -> bool:
 157        """
 158        Checks whether a Literal expression is a string.
 159        """
 160        return isinstance(self, Literal) and self.args["is_string"]
 161
 162    @property
 163    def is_number(self) -> bool:
 164        """
 165        Checks whether a Literal expression is a number.
 166        """
 167        return isinstance(self, Literal) and not self.args["is_string"]
 168
 169    @property
 170    def is_int(self) -> bool:
 171        """
 172        Checks whether a Literal expression is an integer.
 173        """
 174        if self.is_number:
 175            try:
 176                int(self.name)
 177                return True
 178            except ValueError:
 179                pass
 180        return False
 181
 182    @property
 183    def is_star(self) -> bool:
 184        """Checks whether an expression is a star."""
 185        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
 186
 187    @property
 188    def alias(self) -> str:
 189        """
 190        Returns the alias of the expression, or an empty string if it's not aliased.
 191        """
 192        if isinstance(self.args.get("alias"), TableAlias):
 193            return self.args["alias"].name
 194        return self.text("alias")
 195
 196    @property
 197    def name(self) -> str:
 198        return self.text("this")
 199
 200    @property
 201    def alias_or_name(self) -> str:
 202        return self.alias or self.name
 203
 204    @property
 205    def output_name(self) -> str:
 206        """
 207        Name of the output column if this expression is a selection.
 208
 209        If the Expression has no output name, an empty string is returned.
 210
 211        Example:
 212            >>> from sqlglot import parse_one
 213            >>> parse_one("SELECT a").expressions[0].output_name
 214            'a'
 215            >>> parse_one("SELECT b AS c").expressions[0].output_name
 216            'c'
 217            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
 218            ''
 219        """
 220        return ""
 221
 222    @property
 223    def type(self) -> t.Optional[DataType]:
 224        return self._type
 225
 226    @type.setter
 227    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
 228        if dtype and not isinstance(dtype, DataType):
 229            dtype = DataType.build(dtype)
 230        self._type = dtype  # type: ignore
 231
 232    @property
 233    def meta(self) -> t.Dict[str, t.Any]:
 234        if self._meta is None:
 235            self._meta = {}
 236        return self._meta
 237
 238    def __deepcopy__(self, memo):
 239        copy = self.__class__(**deepcopy(self.args))
 240        if self.comments is not None:
 241            copy.comments = deepcopy(self.comments)
 242
 243        if self._type is not None:
 244            copy._type = self._type.copy()
 245
 246        if self._meta is not None:
 247            copy._meta = deepcopy(self._meta)
 248
 249        return copy
 250
 251    def copy(self):
 252        """
 253        Returns a deep copy of the expression.
 254        """
 255        new = deepcopy(self)
 256        new.parent = self.parent
 257        return new
 258
 259    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
 260        if self.comments is None:
 261            self.comments = []
 262        if comments:
 263            self.comments.extend(comments)
 264
 265    def append(self, arg_key: str, value: t.Any) -> None:
 266        """
 267        Appends value to arg_key if it's a list or sets it as a new list.
 268
 269        Args:
 270            arg_key (str): name of the list expression arg
 271            value (Any): value to append to the list
 272        """
 273        if not isinstance(self.args.get(arg_key), list):
 274            self.args[arg_key] = []
 275        self.args[arg_key].append(value)
 276        self._set_parent(arg_key, value)
 277
 278    def set(self, arg_key: str, value: t.Any) -> None:
 279        """
 280        Sets `arg_key` to `value`.
 281
 282        Args:
 283            arg_key (str): name of the expression arg.
 284            value: value to set the arg to.
 285        """
 286        self.args[arg_key] = value
 287        self._set_parent(arg_key, value)
 288
 289    def _set_parent(self, arg_key: str, value: t.Any) -> None:
 290        if hasattr(value, "parent"):
 291            value.parent = self
 292            value.arg_key = arg_key
 293        elif type(value) is list:
 294            for v in value:
 295                if hasattr(v, "parent"):
 296                    v.parent = self
 297                    v.arg_key = arg_key
 298
 299    @property
 300    def depth(self) -> int:
 301        """
 302        Returns the depth of this tree.
 303        """
 304        if self.parent:
 305            return self.parent.depth + 1
 306        return 0
 307
 308    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
 309        """Yields the key and expression for all arguments, exploding list args."""
 310        for k, vs in self.args.items():
 311            if type(vs) is list:
 312                for v in vs:
 313                    if hasattr(v, "parent"):
 314                        yield k, v
 315            else:
 316                if hasattr(vs, "parent"):
 317                    yield k, vs
 318
 319    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
 320        """
 321        Returns the first node in this tree which matches at least one of
 322        the specified types.
 323
 324        Args:
 325            expression_types: the expression type(s) to match.
 326            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
 327
 328        Returns:
 329            The node which matches the criteria or None if no such node was found.
 330        """
 331        return next(self.find_all(*expression_types, bfs=bfs), None)
 332
 333    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
 334        """
 335        Returns a generator object which visits all nodes in this tree and only
 336        yields those that match at least one of the specified expression types.
 337
 338        Args:
 339            expression_types: the expression type(s) to match.
 340            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
 341
 342        Returns:
 343            The generator object.
 344        """
 345        for expression, *_ in self.walk(bfs=bfs):
 346            if isinstance(expression, expression_types):
 347                yield expression
 348
 349    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
 350        """
 351        Returns a nearest parent matching expression_types.
 352
 353        Args:
 354            expression_types: the expression type(s) to match.
 355
 356        Returns:
 357            The parent node.
 358        """
 359        ancestor = self.parent
 360        while ancestor and not isinstance(ancestor, expression_types):
 361            ancestor = ancestor.parent
 362        return t.cast(E, ancestor)
 363
 364    @property
 365    def parent_select(self) -> t.Optional[Select]:
 366        """
 367        Returns the parent select statement.
 368        """
 369        return self.find_ancestor(Select)
 370
 371    @property
 372    def same_parent(self) -> bool:
 373        """Returns if the parent is the same class as itself."""
 374        return type(self.parent) is self.__class__
 375
 376    def root(self) -> Expression:
 377        """
 378        Returns the root expression of this tree.
 379        """
 380        expression = self
 381        while expression.parent:
 382            expression = expression.parent
 383        return expression
 384
 385    def walk(self, bfs=True, prune=None):
 386        """
 387        Returns a generator object which visits all nodes in this tree.
 388
 389        Args:
 390            bfs (bool): if set to True the BFS traversal order will be applied,
 391                otherwise the DFS traversal will be used instead.
 392            prune ((node, parent, arg_key) -> bool): callable that returns True if
 393                the generator should stop traversing this branch of the tree.
 394
 395        Returns:
 396            the generator object.
 397        """
 398        if bfs:
 399            yield from self.bfs(prune=prune)
 400        else:
 401            yield from self.dfs(prune=prune)
 402
 403    def dfs(self, parent=None, key=None, prune=None):
 404        """
 405        Returns a generator object which visits all nodes in this tree in
 406        the DFS (Depth-first) order.
 407
 408        Returns:
 409            The generator object.
 410        """
 411        parent = parent or self.parent
 412        yield self, parent, key
 413        if prune and prune(self, parent, key):
 414            return
 415
 416        for k, v in self.iter_expressions():
 417            yield from v.dfs(self, k, prune)
 418
 419    def bfs(self, prune=None):
 420        """
 421        Returns a generator object which visits all nodes in this tree in
 422        the BFS (Breadth-first) order.
 423
 424        Returns:
 425            The generator object.
 426        """
 427        queue = deque([(self, self.parent, None)])
 428
 429        while queue:
 430            item, parent, key = queue.popleft()
 431
 432            yield item, parent, key
 433            if prune and prune(item, parent, key):
 434                continue
 435
 436            for k, v in item.iter_expressions():
 437                queue.append((v, item, k))
 438
 439    def unnest(self):
 440        """
 441        Returns the first non parenthesis child or self.
 442        """
 443        expression = self
 444        while type(expression) is Paren:
 445            expression = expression.this
 446        return expression
 447
 448    def unalias(self):
 449        """
 450        Returns the inner expression if this is an Alias.
 451        """
 452        if isinstance(self, Alias):
 453            return self.this
 454        return self
 455
 456    def unnest_operands(self):
 457        """
 458        Returns unnested operands as a tuple.
 459        """
 460        return tuple(arg.unnest() for _, arg in self.iter_expressions())
 461
 462    def flatten(self, unnest=True):
 463        """
 464        Returns a generator which yields child nodes who's parents are the same class.
 465
 466        A AND B AND C -> [A, B, C]
 467        """
 468        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
 469            if not type(node) is self.__class__:
 470                yield node.unnest() if unnest else node
 471
 472    def __str__(self) -> str:
 473        return self.sql()
 474
 475    def __repr__(self) -> str:
 476        return self._to_s()
 477
 478    def sql(self, dialect: DialectType = None, **opts) -> str:
 479        """
 480        Returns SQL string representation of this tree.
 481
 482        Args:
 483            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
 484            opts: other `sqlglot.generator.Generator` options.
 485
 486        Returns:
 487            The SQL string.
 488        """
 489        from sqlglot.dialects import Dialect
 490
 491        return Dialect.get_or_raise(dialect)().generate(self, **opts)
 492
 493    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
 494        indent = "" if not level else "\n"
 495        indent += "".join(["  "] * level)
 496        left = f"({self.key.upper()} "
 497
 498        args: t.Dict[str, t.Any] = {
 499            k: ", ".join(
 500                v._to_s(hide_missing=hide_missing, level=level + 1)
 501                if hasattr(v, "_to_s")
 502                else str(v)
 503                for v in ensure_list(vs)
 504                if v is not None
 505            )
 506            for k, vs in self.args.items()
 507        }
 508        args["comments"] = self.comments
 509        args["type"] = self.type
 510        args = {k: v for k, v in args.items() if v or not hide_missing}
 511
 512        right = ", ".join(f"{k}: {v}" for k, v in args.items())
 513        right += ")"
 514
 515        return indent + left + right
 516
 517    def transform(self, fun, *args, copy=True, **kwargs):
 518        """
 519        Recursively visits all tree nodes (excluding already transformed ones)
 520        and applies the given transformation function to each node.
 521
 522        Args:
 523            fun (function): a function which takes a node as an argument and returns a
 524                new transformed node or the same node without modifications. If the function
 525                returns None, then the corresponding node will be removed from the syntax tree.
 526            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
 527                modified in place.
 528
 529        Returns:
 530            The transformed tree.
 531        """
 532        node = self.copy() if copy else self
 533        new_node = fun(node, *args, **kwargs)
 534
 535        if new_node is None or not isinstance(new_node, Expression):
 536            return new_node
 537        if new_node is not node:
 538            new_node.parent = node.parent
 539            return new_node
 540
 541        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
 542        return new_node
 543
 544    @t.overload
 545    def replace(self, expression: E) -> E:
 546        ...
 547
 548    @t.overload
 549    def replace(self, expression: None) -> None:
 550        ...
 551
 552    def replace(self, expression):
 553        """
 554        Swap out this expression with a new expression.
 555
 556        For example::
 557
 558            >>> tree = Select().select("x").from_("tbl")
 559            >>> tree.find(Column).replace(Column(this="y"))
 560            (COLUMN this: y)
 561            >>> tree.sql()
 562            'SELECT y FROM tbl'
 563
 564        Args:
 565            expression: new node
 566
 567        Returns:
 568            The new expression or expressions.
 569        """
 570        if not self.parent:
 571            return expression
 572
 573        parent = self.parent
 574        self.parent = None
 575
 576        replace_children(parent, lambda child: expression if child is self else child)
 577        return expression
 578
 579    def pop(self: E) -> E:
 580        """
 581        Remove this expression from its AST.
 582
 583        Returns:
 584            The popped expression.
 585        """
 586        self.replace(None)
 587        return self
 588
 589    def assert_is(self, type_: t.Type[E]) -> E:
 590        """
 591        Assert that this `Expression` is an instance of `type_`.
 592
 593        If it is NOT an instance of `type_`, this raises an assertion error.
 594        Otherwise, this returns this expression.
 595
 596        Examples:
 597            This is useful for type security in chained expressions:
 598
 599            >>> import sqlglot
 600            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
 601            'SELECT x, z FROM y'
 602        """
 603        assert isinstance(self, type_)
 604        return self
 605
 606    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
 607        """
 608        Checks if this expression is valid (e.g. all mandatory args are set).
 609
 610        Args:
 611            args: a sequence of values that were used to instantiate a Func expression. This is used
 612                to check that the provided arguments don't exceed the function argument limit.
 613
 614        Returns:
 615            A list of error messages for all possible errors that were found.
 616        """
 617        errors: t.List[str] = []
 618
 619        for k in self.args:
 620            if k not in self.arg_types:
 621                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
 622        for k, mandatory in self.arg_types.items():
 623            v = self.args.get(k)
 624            if mandatory and (v is None or (isinstance(v, list) and not v)):
 625                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
 626
 627        if (
 628            args
 629            and isinstance(self, Func)
 630            and len(args) > len(self.arg_types)
 631            and not self.is_var_len_args
 632        ):
 633            errors.append(
 634                f"The number of provided arguments ({len(args)}) is greater than "
 635                f"the maximum number of supported arguments ({len(self.arg_types)})"
 636            )
 637
 638        return errors
 639
 640    def dump(self):
 641        """
 642        Dump this Expression to a JSON-serializable dict.
 643        """
 644        from sqlglot.serde import dump
 645
 646        return dump(self)
 647
 648    @classmethod
 649    def load(cls, obj):
 650        """
 651        Load a dict (as returned by `Expression.dump`) into an Expression instance.
 652        """
 653        from sqlglot.serde import load
 654
 655        return load(obj)
 656
 657
 658IntoType = t.Union[
 659    str,
 660    t.Type[Expression],
 661    t.Collection[t.Union[str, t.Type[Expression]]],
 662]
 663ExpOrStr = t.Union[str, Expression]
 664
 665
 666class Condition(Expression):
 667    def and_(
 668        self,
 669        *expressions: t.Optional[ExpOrStr],
 670        dialect: DialectType = None,
 671        copy: bool = True,
 672        **opts,
 673    ) -> Condition:
 674        """
 675        AND this condition with one or multiple expressions.
 676
 677        Example:
 678            >>> condition("x=1").and_("y=1").sql()
 679            'x = 1 AND y = 1'
 680
 681        Args:
 682            *expressions: the SQL code strings to parse.
 683                If an `Expression` instance is passed, it will be used as-is.
 684            dialect: the dialect used to parse the input expression.
 685            copy: whether or not to copy the involved expressions (only applies to Expressions).
 686            opts: other options to use to parse the input expressions.
 687
 688        Returns:
 689            The new And condition.
 690        """
 691        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
 692
 693    def or_(
 694        self,
 695        *expressions: t.Optional[ExpOrStr],
 696        dialect: DialectType = None,
 697        copy: bool = True,
 698        **opts,
 699    ) -> Condition:
 700        """
 701        OR this condition with one or multiple expressions.
 702
 703        Example:
 704            >>> condition("x=1").or_("y=1").sql()
 705            'x = 1 OR y = 1'
 706
 707        Args:
 708            *expressions: the SQL code strings to parse.
 709                If an `Expression` instance is passed, it will be used as-is.
 710            dialect: the dialect used to parse the input expression.
 711            copy: whether or not to copy the involved expressions (only applies to Expressions).
 712            opts: other options to use to parse the input expressions.
 713
 714        Returns:
 715            The new Or condition.
 716        """
 717        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
 718
 719    def not_(self, copy: bool = True):
 720        """
 721        Wrap this condition with NOT.
 722
 723        Example:
 724            >>> condition("x=1").not_().sql()
 725            'NOT x = 1'
 726
 727        Args:
 728            copy: whether or not to copy this object.
 729
 730        Returns:
 731            The new Not instance.
 732        """
 733        return not_(self, copy=copy)
 734
 735    def as_(
 736        self,
 737        alias: str | Identifier,
 738        quoted: t.Optional[bool] = None,
 739        dialect: DialectType = None,
 740        copy: bool = True,
 741        **opts,
 742    ) -> Alias:
 743        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
 744
 745    def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
 746        this = self.copy()
 747        other = convert(other, copy=True)
 748        if not isinstance(this, klass) and not isinstance(other, klass):
 749            this = _wrap(this, Binary)
 750            other = _wrap(other, Binary)
 751        if reverse:
 752            return klass(this=other, expression=this)
 753        return klass(this=this, expression=other)
 754
 755    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
 756        return Bracket(
 757            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
 758        )
 759
 760    def isin(
 761        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
 762    ) -> In:
 763        return In(
 764            this=_maybe_copy(self, copy),
 765            expressions=[convert(e, copy=copy) for e in expressions],
 766            query=maybe_parse(query, copy=copy, **opts) if query else None,
 767        )
 768
 769    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
 770        return Between(
 771            this=_maybe_copy(self, copy),
 772            low=convert(low, copy=copy, **opts),
 773            high=convert(high, copy=copy, **opts),
 774        )
 775
 776    def is_(self, other: ExpOrStr) -> Is:
 777        return self._binop(Is, other)
 778
 779    def like(self, other: ExpOrStr) -> Like:
 780        return self._binop(Like, other)
 781
 782    def ilike(self, other: ExpOrStr) -> ILike:
 783        return self._binop(ILike, other)
 784
 785    def eq(self, other: t.Any) -> EQ:
 786        return self._binop(EQ, other)
 787
 788    def neq(self, other: t.Any) -> NEQ:
 789        return self._binop(NEQ, other)
 790
 791    def rlike(self, other: ExpOrStr) -> RegexpLike:
 792        return self._binop(RegexpLike, other)
 793
 794    def __lt__(self, other: t.Any) -> LT:
 795        return self._binop(LT, other)
 796
 797    def __le__(self, other: t.Any) -> LTE:
 798        return self._binop(LTE, other)
 799
 800    def __gt__(self, other: t.Any) -> GT:
 801        return self._binop(GT, other)
 802
 803    def __ge__(self, other: t.Any) -> GTE:
 804        return self._binop(GTE, other)
 805
 806    def __add__(self, other: t.Any) -> Add:
 807        return self._binop(Add, other)
 808
 809    def __radd__(self, other: t.Any) -> Add:
 810        return self._binop(Add, other, reverse=True)
 811
 812    def __sub__(self, other: t.Any) -> Sub:
 813        return self._binop(Sub, other)
 814
 815    def __rsub__(self, other: t.Any) -> Sub:
 816        return self._binop(Sub, other, reverse=True)
 817
 818    def __mul__(self, other: t.Any) -> Mul:
 819        return self._binop(Mul, other)
 820
 821    def __rmul__(self, other: t.Any) -> Mul:
 822        return self._binop(Mul, other, reverse=True)
 823
 824    def __truediv__(self, other: t.Any) -> Div:
 825        return self._binop(Div, other)
 826
 827    def __rtruediv__(self, other: t.Any) -> Div:
 828        return self._binop(Div, other, reverse=True)
 829
 830    def __floordiv__(self, other: t.Any) -> IntDiv:
 831        return self._binop(IntDiv, other)
 832
 833    def __rfloordiv__(self, other: t.Any) -> IntDiv:
 834        return self._binop(IntDiv, other, reverse=True)
 835
 836    def __mod__(self, other: t.Any) -> Mod:
 837        return self._binop(Mod, other)
 838
 839    def __rmod__(self, other: t.Any) -> Mod:
 840        return self._binop(Mod, other, reverse=True)
 841
 842    def __pow__(self, other: t.Any) -> Pow:
 843        return self._binop(Pow, other)
 844
 845    def __rpow__(self, other: t.Any) -> Pow:
 846        return self._binop(Pow, other, reverse=True)
 847
 848    def __and__(self, other: t.Any) -> And:
 849        return self._binop(And, other)
 850
 851    def __rand__(self, other: t.Any) -> And:
 852        return self._binop(And, other, reverse=True)
 853
 854    def __or__(self, other: t.Any) -> Or:
 855        return self._binop(Or, other)
 856
 857    def __ror__(self, other: t.Any) -> Or:
 858        return self._binop(Or, other, reverse=True)
 859
 860    def __neg__(self) -> Neg:
 861        return Neg(this=_wrap(self.copy(), Binary))
 862
 863    def __invert__(self) -> Not:
 864        return not_(self.copy())
 865
 866
 867class Predicate(Condition):
 868    """Relationships like x = y, x > 1, x >= y."""
 869
 870
 871class DerivedTable(Expression):
 872    @property
 873    def alias_column_names(self) -> t.List[str]:
 874        table_alias = self.args.get("alias")
 875        if not table_alias:
 876            return []
 877        return [c.name for c in table_alias.args.get("columns") or []]
 878
 879    @property
 880    def selects(self):
 881        return self.this.selects if isinstance(self.this, Subqueryable) else []
 882
 883    @property
 884    def named_selects(self):
 885        return [select.output_name for select in self.selects]
 886
 887
 888class Unionable(Expression):
 889    def union(
 890        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 891    ) -> Unionable:
 892        """
 893        Builds a UNION expression.
 894
 895        Example:
 896            >>> import sqlglot
 897            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
 898            'SELECT * FROM foo UNION SELECT * FROM bla'
 899
 900        Args:
 901            expression: the SQL code string.
 902                If an `Expression` instance is passed, it will be used as-is.
 903            distinct: set the DISTINCT flag if and only if this is true.
 904            dialect: the dialect used to parse the input expression.
 905            opts: other options to use to parse the input expressions.
 906
 907        Returns:
 908            The new Union expression.
 909        """
 910        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 911
 912    def intersect(
 913        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 914    ) -> Unionable:
 915        """
 916        Builds an INTERSECT expression.
 917
 918        Example:
 919            >>> import sqlglot
 920            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
 921            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
 922
 923        Args:
 924            expression: the SQL code string.
 925                If an `Expression` instance is passed, it will be used as-is.
 926            distinct: set the DISTINCT flag if and only if this is true.
 927            dialect: the dialect used to parse the input expression.
 928            opts: other options to use to parse the input expressions.
 929
 930        Returns:
 931            The new Intersect expression.
 932        """
 933        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 934
 935    def except_(
 936        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 937    ) -> Unionable:
 938        """
 939        Builds an EXCEPT expression.
 940
 941        Example:
 942            >>> import sqlglot
 943            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
 944            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
 945
 946        Args:
 947            expression: the SQL code string.
 948                If an `Expression` instance is passed, it will be used as-is.
 949            distinct: set the DISTINCT flag if and only if this is true.
 950            dialect: the dialect used to parse the input expression.
 951            opts: other options to use to parse the input expressions.
 952
 953        Returns:
 954            The new Except expression.
 955        """
 956        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 957
 958
 959class UDTF(DerivedTable, Unionable):
 960    @property
 961    def selects(self):
 962        alias = self.args.get("alias")
 963        return alias.columns if alias else []
 964
 965
 966class Cache(Expression):
 967    arg_types = {
 968        "with": False,
 969        "this": True,
 970        "lazy": False,
 971        "options": False,
 972        "expression": False,
 973    }
 974
 975
 976class Uncache(Expression):
 977    arg_types = {"this": True, "exists": False}
 978
 979
 980class Create(Expression):
 981    arg_types = {
 982        "with": False,
 983        "this": True,
 984        "kind": True,
 985        "expression": False,
 986        "exists": False,
 987        "properties": False,
 988        "replace": False,
 989        "unique": False,
 990        "indexes": False,
 991        "no_schema_binding": False,
 992        "begin": False,
 993        "clone": False,
 994    }
 995
 996
 997# https://docs.snowflake.com/en/sql-reference/sql/create-clone
 998class Clone(Expression):
 999    arg_types = {
1000        "this": True,
1001        "when": False,
1002        "kind": False,
1003        "expression": False,
1004    }
1005
1006
1007class Describe(Expression):
1008    arg_types = {"this": True, "kind": False}
1009
1010
1011class Pragma(Expression):
1012    pass
1013
1014
1015class Set(Expression):
1016    arg_types = {"expressions": False, "unset": False, "tag": False}
1017
1018
1019class SetItem(Expression):
1020    arg_types = {
1021        "this": False,
1022        "expressions": False,
1023        "kind": False,
1024        "collate": False,  # MySQL SET NAMES statement
1025        "global": False,
1026    }
1027
1028
1029class Show(Expression):
1030    arg_types = {
1031        "this": True,
1032        "target": False,
1033        "offset": False,
1034        "limit": False,
1035        "like": False,
1036        "where": False,
1037        "db": False,
1038        "full": False,
1039        "mutex": False,
1040        "query": False,
1041        "channel": False,
1042        "global": False,
1043        "log": False,
1044        "position": False,
1045        "types": False,
1046    }
1047
1048
1049class UserDefinedFunction(Expression):
1050    arg_types = {"this": True, "expressions": False, "wrapped": False}
1051
1052
1053class CharacterSet(Expression):
1054    arg_types = {"this": True, "default": False}
1055
1056
1057class With(Expression):
1058    arg_types = {"expressions": True, "recursive": False}
1059
1060    @property
1061    def recursive(self) -> bool:
1062        return bool(self.args.get("recursive"))
1063
1064
1065class WithinGroup(Expression):
1066    arg_types = {"this": True, "expression": False}
1067
1068
1069class CTE(DerivedTable):
1070    arg_types = {"this": True, "alias": True}
1071
1072
1073class TableAlias(Expression):
1074    arg_types = {"this": False, "columns": False}
1075
1076    @property
1077    def columns(self):
1078        return self.args.get("columns") or []
1079
1080
1081class BitString(Condition):
1082    pass
1083
1084
1085class HexString(Condition):
1086    pass
1087
1088
1089class ByteString(Condition):
1090    pass
1091
1092
1093class RawString(Condition):
1094    pass
1095
1096
1097class Column(Condition):
1098    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1099
1100    @property
1101    def table(self) -> str:
1102        return self.text("table")
1103
1104    @property
1105    def db(self) -> str:
1106        return self.text("db")
1107
1108    @property
1109    def catalog(self) -> str:
1110        return self.text("catalog")
1111
1112    @property
1113    def output_name(self) -> str:
1114        return self.name
1115
1116    @property
1117    def parts(self) -> t.List[Identifier]:
1118        """Return the parts of a column in order catalog, db, table, name."""
1119        return [
1120            t.cast(Identifier, self.args[part])
1121            for part in ("catalog", "db", "table", "this")
1122            if self.args.get(part)
1123        ]
1124
1125    def to_dot(self) -> Dot:
1126        """Converts the column into a dot expression."""
1127        parts = self.parts
1128        parent = self.parent
1129
1130        while parent:
1131            if isinstance(parent, Dot):
1132                parts.append(parent.expression)
1133            parent = parent.parent
1134
1135        return Dot.build(parts)
1136
1137
1138class ColumnPosition(Expression):
1139    arg_types = {"this": False, "position": True}
1140
1141
1142class ColumnDef(Expression):
1143    arg_types = {
1144        "this": True,
1145        "kind": False,
1146        "constraints": False,
1147        "exists": False,
1148        "position": False,
1149    }
1150
1151    @property
1152    def constraints(self) -> t.List[ColumnConstraint]:
1153        return self.args.get("constraints") or []
1154
1155
1156class AlterColumn(Expression):
1157    arg_types = {
1158        "this": True,
1159        "dtype": False,
1160        "collate": False,
1161        "using": False,
1162        "default": False,
1163        "drop": False,
1164    }
1165
1166
1167class RenameTable(Expression):
1168    pass
1169
1170
1171class Comment(Expression):
1172    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
1173
1174
1175# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl
1176class MergeTreeTTLAction(Expression):
1177    arg_types = {
1178        "this": True,
1179        "delete": False,
1180        "recompress": False,
1181        "to_disk": False,
1182        "to_volume": False,
1183    }
1184
1185
1186# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl
1187class MergeTreeTTL(Expression):
1188    arg_types = {
1189        "expressions": True,
1190        "where": False,
1191        "group": False,
1192        "aggregates": False,
1193    }
1194
1195
1196class ColumnConstraint(Expression):
1197    arg_types = {"this": False, "kind": True}
1198
1199    @property
1200    def kind(self) -> ColumnConstraintKind:
1201        return self.args["kind"]
1202
1203
1204class ColumnConstraintKind(Expression):
1205    pass
1206
1207
1208class AutoIncrementColumnConstraint(ColumnConstraintKind):
1209    pass
1210
1211
1212class CaseSpecificColumnConstraint(ColumnConstraintKind):
1213    arg_types = {"not_": True}
1214
1215
1216class CharacterSetColumnConstraint(ColumnConstraintKind):
1217    arg_types = {"this": True}
1218
1219
1220class CheckColumnConstraint(ColumnConstraintKind):
1221    pass
1222
1223
1224class CollateColumnConstraint(ColumnConstraintKind):
1225    pass
1226
1227
1228class CommentColumnConstraint(ColumnConstraintKind):
1229    pass
1230
1231
1232class CompressColumnConstraint(ColumnConstraintKind):
1233    pass
1234
1235
1236class DateFormatColumnConstraint(ColumnConstraintKind):
1237    arg_types = {"this": True}
1238
1239
1240class DefaultColumnConstraint(ColumnConstraintKind):
1241    pass
1242
1243
1244class EncodeColumnConstraint(ColumnConstraintKind):
1245    pass
1246
1247
1248class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1249    # this: True -> ALWAYS, this: False -> BY DEFAULT
1250    arg_types = {
1251        "this": False,
1252        "expression": False,
1253        "on_null": False,
1254        "start": False,
1255        "increment": False,
1256        "minvalue": False,
1257        "maxvalue": False,
1258        "cycle": False,
1259    }
1260
1261
1262class InlineLengthColumnConstraint(ColumnConstraintKind):
1263    pass
1264
1265
1266class NotNullColumnConstraint(ColumnConstraintKind):
1267    arg_types = {"allow_null": False}
1268
1269
1270# https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
1271class OnUpdateColumnConstraint(ColumnConstraintKind):
1272    pass
1273
1274
1275class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1276    arg_types = {"desc": False}
1277
1278
1279class TitleColumnConstraint(ColumnConstraintKind):
1280    pass
1281
1282
1283class UniqueColumnConstraint(ColumnConstraintKind):
1284    arg_types = {"this": False}
1285
1286
1287class UppercaseColumnConstraint(ColumnConstraintKind):
1288    arg_types: t.Dict[str, t.Any] = {}
1289
1290
1291class PathColumnConstraint(ColumnConstraintKind):
1292    pass
1293
1294
1295class Constraint(Expression):
1296    arg_types = {"this": True, "expressions": True}
1297
1298
1299class Delete(Expression):
1300    arg_types = {
1301        "with": False,
1302        "this": False,
1303        "using": False,
1304        "where": False,
1305        "returning": False,
1306        "limit": False,
1307    }
1308
1309    def delete(
1310        self,
1311        table: ExpOrStr,
1312        dialect: DialectType = None,
1313        copy: bool = True,
1314        **opts,
1315    ) -> Delete:
1316        """
1317        Create a DELETE expression or replace the table on an existing DELETE expression.
1318
1319        Example:
1320            >>> delete("tbl").sql()
1321            'DELETE FROM tbl'
1322
1323        Args:
1324            table: the table from which to delete.
1325            dialect: the dialect used to parse the input expression.
1326            copy: if `False`, modify this expression instance in-place.
1327            opts: other options to use to parse the input expressions.
1328
1329        Returns:
1330            Delete: the modified expression.
1331        """
1332        return _apply_builder(
1333            expression=table,
1334            instance=self,
1335            arg="this",
1336            dialect=dialect,
1337            into=Table,
1338            copy=copy,
1339            **opts,
1340        )
1341
1342    def where(
1343        self,
1344        *expressions: t.Optional[ExpOrStr],
1345        append: bool = True,
1346        dialect: DialectType = None,
1347        copy: bool = True,
1348        **opts,
1349    ) -> Delete:
1350        """
1351        Append to or set the WHERE expressions.
1352
1353        Example:
1354            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1355            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1356
1357        Args:
1358            *expressions: the SQL code strings to parse.
1359                If an `Expression` instance is passed, it will be used as-is.
1360                Multiple expressions are combined with an AND operator.
1361            append: if `True`, AND the new expressions to any existing expression.
1362                Otherwise, this resets the expression.
1363            dialect: the dialect used to parse the input expressions.
1364            copy: if `False`, modify this expression instance in-place.
1365            opts: other options to use to parse the input expressions.
1366
1367        Returns:
1368            Delete: the modified expression.
1369        """
1370        return _apply_conjunction_builder(
1371            *expressions,
1372            instance=self,
1373            arg="where",
1374            append=append,
1375            into=Where,
1376            dialect=dialect,
1377            copy=copy,
1378            **opts,
1379        )
1380
1381    def returning(
1382        self,
1383        expression: ExpOrStr,
1384        dialect: DialectType = None,
1385        copy: bool = True,
1386        **opts,
1387    ) -> Delete:
1388        """
1389        Set the RETURNING expression. Not supported by all dialects.
1390
1391        Example:
1392            >>> delete("tbl").returning("*", dialect="postgres").sql()
1393            'DELETE FROM tbl RETURNING *'
1394
1395        Args:
1396            expression: the SQL code strings to parse.
1397                If an `Expression` instance is passed, it will be used as-is.
1398            dialect: the dialect used to parse the input expressions.
1399            copy: if `False`, modify this expression instance in-place.
1400            opts: other options to use to parse the input expressions.
1401
1402        Returns:
1403            Delete: the modified expression.
1404        """
1405        return _apply_builder(
1406            expression=expression,
1407            instance=self,
1408            arg="returning",
1409            prefix="RETURNING",
1410            dialect=dialect,
1411            copy=copy,
1412            into=Returning,
1413            **opts,
1414        )
1415
1416
1417class Drop(Expression):
1418    arg_types = {
1419        "this": False,
1420        "kind": False,
1421        "exists": False,
1422        "temporary": False,
1423        "materialized": False,
1424        "cascade": False,
1425        "constraints": False,
1426        "purge": False,
1427    }
1428
1429
1430class Filter(Expression):
1431    arg_types = {"this": True, "expression": True}
1432
1433
1434class Check(Expression):
1435    pass
1436
1437
1438class Directory(Expression):
1439    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1440    arg_types = {"this": True, "local": False, "row_format": False}
1441
1442
1443class ForeignKey(Expression):
1444    arg_types = {
1445        "expressions": True,
1446        "reference": False,
1447        "delete": False,
1448        "update": False,
1449    }
1450
1451
1452class PrimaryKey(Expression):
1453    arg_types = {"expressions": True, "options": False}
1454
1455
1456# https://www.postgresql.org/docs/9.1/sql-selectinto.html
1457# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples
1458class Into(Expression):
1459    arg_types = {"this": True, "temporary": False, "unlogged": False}
1460
1461
1462class From(Expression):
1463    @property
1464    def name(self) -> str:
1465        return self.this.name
1466
1467    @property
1468    def alias_or_name(self) -> str:
1469        return self.this.alias_or_name
1470
1471
1472class Having(Expression):
1473    pass
1474
1475
1476class Hint(Expression):
1477    arg_types = {"expressions": True}
1478
1479
1480class JoinHint(Expression):
1481    arg_types = {"this": True, "expressions": True}
1482
1483
1484class Identifier(Expression):
1485    arg_types = {"this": True, "quoted": False}
1486
1487    @property
1488    def quoted(self) -> bool:
1489        return bool(self.args.get("quoted"))
1490
1491    @property
1492    def hashable_args(self) -> t.Any:
1493        if self.quoted and any(char.isupper() for char in self.this):
1494            return (self.this, self.quoted)
1495        return self.this.lower()
1496
1497    @property
1498    def output_name(self) -> str:
1499        return self.name
1500
1501
1502class Index(Expression):
1503    arg_types = {
1504        "this": False,
1505        "table": False,
1506        "using": False,
1507        "where": False,
1508        "columns": False,
1509        "unique": False,
1510        "primary": False,
1511        "amp": False,  # teradata
1512        "partition_by": False,  # teradata
1513    }
1514
1515
1516class Insert(Expression):
1517    arg_types = {
1518        "with": False,
1519        "this": True,
1520        "expression": False,
1521        "conflict": False,
1522        "returning": False,
1523        "overwrite": False,
1524        "exists": False,
1525        "partition": False,
1526        "alternative": False,
1527        "where": False,
1528    }
1529
1530    def with_(
1531        self,
1532        alias: ExpOrStr,
1533        as_: ExpOrStr,
1534        recursive: t.Optional[bool] = None,
1535        append: bool = True,
1536        dialect: DialectType = None,
1537        copy: bool = True,
1538        **opts,
1539    ) -> Insert:
1540        """
1541        Append to or set the common table expressions.
1542
1543        Example:
1544            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1545            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1546
1547        Args:
1548            alias: the SQL code string to parse as the table name.
1549                If an `Expression` instance is passed, this is used as-is.
1550            as_: the SQL code string to parse as the table expression.
1551                If an `Expression` instance is passed, it will be used as-is.
1552            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1553            append: if `True`, add to any existing expressions.
1554                Otherwise, this resets the expressions.
1555            dialect: the dialect used to parse the input expression.
1556            copy: if `False`, modify this expression instance in-place.
1557            opts: other options to use to parse the input expressions.
1558
1559        Returns:
1560            The modified expression.
1561        """
1562        return _apply_cte_builder(
1563            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1564        )
1565
1566
1567class OnConflict(Expression):
1568    arg_types = {
1569        "duplicate": False,
1570        "expressions": False,
1571        "nothing": False,
1572        "key": False,
1573        "constraint": False,
1574    }
1575
1576
1577class Returning(Expression):
1578    arg_types = {"expressions": True}
1579
1580
1581# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1582class Introducer(Expression):
1583    arg_types = {"this": True, "expression": True}
1584
1585
1586# national char, like n'utf8'
1587class National(Expression):
1588    pass
1589
1590
1591class LoadData(Expression):
1592    arg_types = {
1593        "this": True,
1594        "local": False,
1595        "overwrite": False,
1596        "inpath": True,
1597        "partition": False,
1598        "input_format": False,
1599        "serde": False,
1600    }
1601
1602
1603class Partition(Expression):
1604    arg_types = {"expressions": True}
1605
1606
1607class Fetch(Expression):
1608    arg_types = {
1609        "direction": False,
1610        "count": False,
1611        "percent": False,
1612        "with_ties": False,
1613    }
1614
1615
1616class Group(Expression):
1617    arg_types = {
1618        "expressions": False,
1619        "grouping_sets": False,
1620        "cube": False,
1621        "rollup": False,
1622        "totals": False,
1623    }
1624
1625
1626class Lambda(Expression):
1627    arg_types = {"this": True, "expressions": True}
1628
1629
1630class Limit(Expression):
1631    arg_types = {"this": False, "expression": True, "offset": False}
1632
1633
1634class Literal(Condition):
1635    arg_types = {"this": True, "is_string": True}
1636
1637    @property
1638    def hashable_args(self) -> t.Any:
1639        return (self.this, self.args.get("is_string"))
1640
1641    @classmethod
1642    def number(cls, number) -> Literal:
1643        return cls(this=str(number), is_string=False)
1644
1645    @classmethod
1646    def string(cls, string) -> Literal:
1647        return cls(this=str(string), is_string=True)
1648
1649    @property
1650    def output_name(self) -> str:
1651        return self.name
1652
1653
1654class Join(Expression):
1655    arg_types = {
1656        "this": True,
1657        "on": False,
1658        "side": False,
1659        "kind": False,
1660        "using": False,
1661        "method": False,
1662        "global": False,
1663        "hint": False,
1664    }
1665
1666    @property
1667    def method(self) -> str:
1668        return self.text("method").upper()
1669
1670    @property
1671    def kind(self) -> str:
1672        return self.text("kind").upper()
1673
1674    @property
1675    def side(self) -> str:
1676        return self.text("side").upper()
1677
1678    @property
1679    def hint(self) -> str:
1680        return self.text("hint").upper()
1681
1682    @property
1683    def alias_or_name(self) -> str:
1684        return self.this.alias_or_name
1685
1686    def on(
1687        self,
1688        *expressions: t.Optional[ExpOrStr],
1689        append: bool = True,
1690        dialect: DialectType = None,
1691        copy: bool = True,
1692        **opts,
1693    ) -> Join:
1694        """
1695        Append to or set the ON expressions.
1696
1697        Example:
1698            >>> import sqlglot
1699            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1700            'JOIN x ON y = 1'
1701
1702        Args:
1703            *expressions: the SQL code strings to parse.
1704                If an `Expression` instance is passed, it will be used as-is.
1705                Multiple expressions are combined with an AND operator.
1706            append: if `True`, AND the new expressions to any existing expression.
1707                Otherwise, this resets the expression.
1708            dialect: the dialect used to parse the input expressions.
1709            copy: if `False`, modify this expression instance in-place.
1710            opts: other options to use to parse the input expressions.
1711
1712        Returns:
1713            The modified Join expression.
1714        """
1715        join = _apply_conjunction_builder(
1716            *expressions,
1717            instance=self,
1718            arg="on",
1719            append=append,
1720            dialect=dialect,
1721            copy=copy,
1722            **opts,
1723        )
1724
1725        if join.kind == "CROSS":
1726            join.set("kind", None)
1727
1728        return join
1729
1730    def using(
1731        self,
1732        *expressions: t.Optional[ExpOrStr],
1733        append: bool = True,
1734        dialect: DialectType = None,
1735        copy: bool = True,
1736        **opts,
1737    ) -> Join:
1738        """
1739        Append to or set the USING expressions.
1740
1741        Example:
1742            >>> import sqlglot
1743            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1744            'JOIN x USING (foo, bla)'
1745
1746        Args:
1747            *expressions: the SQL code strings to parse.
1748                If an `Expression` instance is passed, it will be used as-is.
1749            append: if `True`, concatenate the new expressions to the existing "using" list.
1750                Otherwise, this resets the expression.
1751            dialect: the dialect used to parse the input expressions.
1752            copy: if `False`, modify this expression instance in-place.
1753            opts: other options to use to parse the input expressions.
1754
1755        Returns:
1756            The modified Join expression.
1757        """
1758        join = _apply_list_builder(
1759            *expressions,
1760            instance=self,
1761            arg="using",
1762            append=append,
1763            dialect=dialect,
1764            copy=copy,
1765            **opts,
1766        )
1767
1768        if join.kind == "CROSS":
1769            join.set("kind", None)
1770
1771        return join
1772
1773
1774class Lateral(UDTF):
1775    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
1776
1777
1778class MatchRecognize(Expression):
1779    arg_types = {
1780        "partition_by": False,
1781        "order": False,
1782        "measures": False,
1783        "rows": False,
1784        "after": False,
1785        "pattern": False,
1786        "define": False,
1787        "alias": False,
1788    }
1789
1790
1791# Clickhouse FROM FINAL modifier
1792# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier
1793class Final(Expression):
1794    pass
1795
1796
1797class Offset(Expression):
1798    arg_types = {"this": False, "expression": True}
1799
1800
1801class Order(Expression):
1802    arg_types = {"this": False, "expressions": True}
1803
1804
1805# hive specific sorts
1806# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy
1807class Cluster(Order):
1808    pass
1809
1810
1811class Distribute(Order):
1812    pass
1813
1814
1815class Sort(Order):
1816    pass
1817
1818
1819class Ordered(Expression):
1820    arg_types = {"this": True, "desc": True, "nulls_first": True}
1821
1822
1823class Property(Expression):
1824    arg_types = {"this": True, "value": True}
1825
1826
1827class AlgorithmProperty(Property):
1828    arg_types = {"this": True}
1829
1830
1831class AutoIncrementProperty(Property):
1832    arg_types = {"this": True}
1833
1834
1835class BlockCompressionProperty(Property):
1836    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
1837
1838
1839class CharacterSetProperty(Property):
1840    arg_types = {"this": True, "default": True}
1841
1842
1843class ChecksumProperty(Property):
1844    arg_types = {"on": False, "default": False}
1845
1846
1847class CollateProperty(Property):
1848    arg_types = {"this": True}
1849
1850
1851class CopyGrantsProperty(Property):
1852    arg_types = {}
1853
1854
1855class DataBlocksizeProperty(Property):
1856    arg_types = {
1857        "size": False,
1858        "units": False,
1859        "minimum": False,
1860        "maximum": False,
1861        "default": False,
1862    }
1863
1864
1865class DefinerProperty(Property):
1866    arg_types = {"this": True}
1867
1868
1869class DistKeyProperty(Property):
1870    arg_types = {"this": True}
1871
1872
1873class DistStyleProperty(Property):
1874    arg_types = {"this": True}
1875
1876
1877class EngineProperty(Property):
1878    arg_types = {"this": True}
1879
1880
1881class ToTableProperty(Property):
1882    arg_types = {"this": True}
1883
1884
1885class ExecuteAsProperty(Property):
1886    arg_types = {"this": True}
1887
1888
1889class ExternalProperty(Property):
1890    arg_types = {"this": False}
1891
1892
1893class FallbackProperty(Property):
1894    arg_types = {"no": True, "protection": False}
1895
1896
1897class FileFormatProperty(Property):
1898    arg_types = {"this": True}
1899
1900
1901class FreespaceProperty(Property):
1902    arg_types = {"this": True, "percent": False}
1903
1904
1905class InputOutputFormat(Expression):
1906    arg_types = {"input_format": False, "output_format": False}
1907
1908
1909class IsolatedLoadingProperty(Property):
1910    arg_types = {
1911        "no": True,
1912        "concurrent": True,
1913        "for_all": True,
1914        "for_insert": True,
1915        "for_none": True,
1916    }
1917
1918
1919class JournalProperty(Property):
1920    arg_types = {
1921        "no": False,
1922        "dual": False,
1923        "before": False,
1924        "local": False,
1925        "after": False,
1926    }
1927
1928
1929class LanguageProperty(Property):
1930    arg_types = {"this": True}
1931
1932
1933# spark ddl
1934class ClusteredByProperty(Property):
1935    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
1936
1937
1938class DictProperty(Property):
1939    arg_types = {"this": True, "kind": True, "settings": False}
1940
1941
1942class DictSubProperty(Property):
1943    pass
1944
1945
1946class DictRange(Property):
1947    arg_types = {"this": True, "min": True, "max": True}
1948
1949
1950# Clickhouse CREATE ... ON CLUSTER modifier
1951# https://clickhouse.com/docs/en/sql-reference/distributed-ddl
1952class OnCluster(Property):
1953    arg_types = {"this": True}
1954
1955
1956class LikeProperty(Property):
1957    arg_types = {"this": True, "expressions": False}
1958
1959
1960class LocationProperty(Property):
1961    arg_types = {"this": True}
1962
1963
1964class LockingProperty(Property):
1965    arg_types = {
1966        "this": False,
1967        "kind": True,
1968        "for_or_in": True,
1969        "lock_type": True,
1970        "override": False,
1971    }
1972
1973
1974class LogProperty(Property):
1975    arg_types = {"no": True}
1976
1977
1978class MaterializedProperty(Property):
1979    arg_types = {"this": False}
1980
1981
1982class MergeBlockRatioProperty(Property):
1983    arg_types = {"this": False, "no": False, "default": False, "percent": False}
1984
1985
1986class NoPrimaryIndexProperty(Property):
1987    arg_types = {}
1988
1989
1990class OnCommitProperty(Property):
1991    arg_type = {"delete": False}
1992
1993
1994class PartitionedByProperty(Property):
1995    arg_types = {"this": True}
1996
1997
1998class ReturnsProperty(Property):
1999    arg_types = {"this": True, "is_table": False, "table": False}
2000
2001
2002class RowFormatProperty(Property):
2003    arg_types = {"this": True}
2004
2005
2006class RowFormatDelimitedProperty(Property):
2007    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2008    arg_types = {
2009        "fields": False,
2010        "escaped": False,
2011        "collection_items": False,
2012        "map_keys": False,
2013        "lines": False,
2014        "null": False,
2015        "serde": False,
2016    }
2017
2018
2019class RowFormatSerdeProperty(Property):
2020    arg_types = {"this": True}
2021
2022
2023class SchemaCommentProperty(Property):
2024    arg_types = {"this": True}
2025
2026
2027class SerdeProperties(Property):
2028    arg_types = {"expressions": True}
2029
2030
2031class SetProperty(Property):
2032    arg_types = {"multi": True}
2033
2034
2035class SettingsProperty(Property):
2036    arg_types = {"expressions": True}
2037
2038
2039class SortKeyProperty(Property):
2040    arg_types = {"this": True, "compound": False}
2041
2042
2043class SqlSecurityProperty(Property):
2044    arg_types = {"definer": True}
2045
2046
2047class StabilityProperty(Property):
2048    arg_types = {"this": True}
2049
2050
2051class TemporaryProperty(Property):
2052    arg_types = {}
2053
2054
2055class TransientProperty(Property):
2056    arg_types = {"this": False}
2057
2058
2059class VolatileProperty(Property):
2060    arg_types = {"this": False}
2061
2062
2063class WithDataProperty(Property):
2064    arg_types = {"no": True, "statistics": False}
2065
2066
2067class WithJournalTableProperty(Property):
2068    arg_types = {"this": True}
2069
2070
2071class Properties(Expression):
2072    arg_types = {"expressions": True}
2073
2074    NAME_TO_PROPERTY = {
2075        "ALGORITHM": AlgorithmProperty,
2076        "AUTO_INCREMENT": AutoIncrementProperty,
2077        "CHARACTER SET": CharacterSetProperty,
2078        "CLUSTERED_BY": ClusteredByProperty,
2079        "COLLATE": CollateProperty,
2080        "COMMENT": SchemaCommentProperty,
2081        "DEFINER": DefinerProperty,
2082        "DISTKEY": DistKeyProperty,
2083        "DISTSTYLE": DistStyleProperty,
2084        "ENGINE": EngineProperty,
2085        "EXECUTE AS": ExecuteAsProperty,
2086        "FORMAT": FileFormatProperty,
2087        "LANGUAGE": LanguageProperty,
2088        "LOCATION": LocationProperty,
2089        "PARTITIONED_BY": PartitionedByProperty,
2090        "RETURNS": ReturnsProperty,
2091        "ROW_FORMAT": RowFormatProperty,
2092        "SORTKEY": SortKeyProperty,
2093    }
2094
2095    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2096
2097    # CREATE property locations
2098    # Form: schema specified
2099    #   create [POST_CREATE]
2100    #     table a [POST_NAME]
2101    #     (b int) [POST_SCHEMA]
2102    #     with ([POST_WITH])
2103    #     index (b) [POST_INDEX]
2104    #
2105    # Form: alias selection
2106    #   create [POST_CREATE]
2107    #     table a [POST_NAME]
2108    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2109    #     index (c) [POST_INDEX]
2110    class Location(AutoName):
2111        POST_CREATE = auto()
2112        POST_NAME = auto()
2113        POST_SCHEMA = auto()
2114        POST_WITH = auto()
2115        POST_ALIAS = auto()
2116        POST_EXPRESSION = auto()
2117        POST_INDEX = auto()
2118        UNSUPPORTED = auto()
2119
2120    @classmethod
2121    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2122        expressions = []
2123        for key, value in properties_dict.items():
2124            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2125            if property_cls:
2126                expressions.append(property_cls(this=convert(value)))
2127            else:
2128                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2129
2130        return cls(expressions=expressions)
2131
2132
2133class Qualify(Expression):
2134    pass
2135
2136
2137# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql
2138class Return(Expression):
2139    pass
2140
2141
2142class Reference(Expression):
2143    arg_types = {"this": True, "expressions": False, "options": False}
2144
2145
2146class Tuple(Expression):
2147    arg_types = {"expressions": False}
2148
2149    def isin(
2150        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2151    ) -> In:
2152        return In(
2153            this=_maybe_copy(self, copy),
2154            expressions=[convert(e, copy=copy) for e in expressions],
2155            query=maybe_parse(query, copy=copy, **opts) if query else None,
2156        )
2157
2158
2159class Subqueryable(Unionable):
2160    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2161        """
2162        Convert this expression to an aliased expression that can be used as a Subquery.
2163
2164        Example:
2165            >>> subquery = Select().select("x").from_("tbl").subquery()
2166            >>> Select().select("x").from_(subquery).sql()
2167            'SELECT x FROM (SELECT x FROM tbl)'
2168
2169        Args:
2170            alias (str | Identifier): an optional alias for the subquery
2171            copy (bool): if `False`, modify this expression instance in-place.
2172
2173        Returns:
2174            Alias: the subquery
2175        """
2176        instance = _maybe_copy(self, copy)
2177        if not isinstance(alias, Expression):
2178            alias = TableAlias(this=to_identifier(alias)) if alias else None
2179
2180        return Subquery(this=instance, alias=alias)
2181
2182    def limit(
2183        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2184    ) -> Select:
2185        raise NotImplementedError
2186
2187    @property
2188    def ctes(self):
2189        with_ = self.args.get("with")
2190        if not with_:
2191            return []
2192        return with_.expressions
2193
2194    @property
2195    def selects(self):
2196        raise NotImplementedError("Subqueryable objects must implement `selects`")
2197
2198    @property
2199    def named_selects(self):
2200        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2201
2202    def with_(
2203        self,
2204        alias: ExpOrStr,
2205        as_: ExpOrStr,
2206        recursive: t.Optional[bool] = None,
2207        append: bool = True,
2208        dialect: DialectType = None,
2209        copy: bool = True,
2210        **opts,
2211    ) -> Subqueryable:
2212        """
2213        Append to or set the common table expressions.
2214
2215        Example:
2216            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2217            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2218
2219        Args:
2220            alias: the SQL code string to parse as the table name.
2221                If an `Expression` instance is passed, this is used as-is.
2222            as_: the SQL code string to parse as the table expression.
2223                If an `Expression` instance is passed, it will be used as-is.
2224            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2225            append: if `True`, add to any existing expressions.
2226                Otherwise, this resets the expressions.
2227            dialect: the dialect used to parse the input expression.
2228            copy: if `False`, modify this expression instance in-place.
2229            opts: other options to use to parse the input expressions.
2230
2231        Returns:
2232            The modified expression.
2233        """
2234        return _apply_cte_builder(
2235            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2236        )
2237
2238
2239QUERY_MODIFIERS = {
2240    "match": False,
2241    "laterals": False,
2242    "joins": False,
2243    "pivots": False,
2244    "where": False,
2245    "group": False,
2246    "having": False,
2247    "qualify": False,
2248    "windows": False,
2249    "distribute": False,
2250    "sort": False,
2251    "cluster": False,
2252    "order": False,
2253    "limit": False,
2254    "offset": False,
2255    "locks": False,
2256    "sample": False,
2257    "settings": False,
2258    "format": False,
2259}
2260
2261
2262# https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table?view=sql-server-ver16
2263class WithTableHint(Expression):
2264    arg_types = {"expressions": True}
2265
2266
2267# https://dev.mysql.com/doc/refman/8.0/en/index-hints.html
2268class IndexTableHint(Expression):
2269    arg_types = {"this": True, "expressions": False, "target": False}
2270
2271
2272class Table(Expression):
2273    arg_types = {
2274        "this": True,
2275        "alias": False,
2276        "db": False,
2277        "catalog": False,
2278        "laterals": False,
2279        "joins": False,
2280        "pivots": False,
2281        "hints": False,
2282        "system_time": False,
2283    }
2284
2285    @property
2286    def db(self) -> str:
2287        return self.text("db")
2288
2289    @property
2290    def catalog(self) -> str:
2291        return self.text("catalog")
2292
2293    @property
2294    def parts(self) -> t.List[Identifier]:
2295        """Return the parts of a table in order catalog, db, table."""
2296        return [
2297            t.cast(Identifier, self.args[part])
2298            for part in ("catalog", "db", "this")
2299            if self.args.get(part)
2300        ]
2301
2302
2303# See the TSQL "Querying data in a system-versioned temporal table" page
2304class SystemTime(Expression):
2305    arg_types = {
2306        "this": False,
2307        "expression": False,
2308        "kind": True,
2309    }
2310
2311
2312class Union(Subqueryable):
2313    arg_types = {
2314        "with": False,
2315        "this": True,
2316        "expression": True,
2317        "distinct": False,
2318        **QUERY_MODIFIERS,
2319    }
2320
2321    def limit(
2322        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2323    ) -> Select:
2324        """
2325        Set the LIMIT expression.
2326
2327        Example:
2328            >>> select("1").union(select("1")).limit(1).sql()
2329            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2330
2331        Args:
2332            expression: the SQL code string to parse.
2333                This can also be an integer.
2334                If a `Limit` instance is passed, this is used as-is.
2335                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2336            dialect: the dialect used to parse the input expression.
2337            copy: if `False`, modify this expression instance in-place.
2338            opts: other options to use to parse the input expressions.
2339
2340        Returns:
2341            The limited subqueryable.
2342        """
2343        return (
2344            select("*")
2345            .from_(self.subquery(alias="_l_0", copy=copy))
2346            .limit(expression, dialect=dialect, copy=False, **opts)
2347        )
2348
2349    def select(
2350        self,
2351        *expressions: t.Optional[ExpOrStr],
2352        append: bool = True,
2353        dialect: DialectType = None,
2354        copy: bool = True,
2355        **opts,
2356    ) -> Union:
2357        """Append to or set the SELECT of the union recursively.
2358
2359        Example:
2360            >>> from sqlglot import parse_one
2361            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2362            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2363
2364        Args:
2365            *expressions: the SQL code strings to parse.
2366                If an `Expression` instance is passed, it will be used as-is.
2367            append: if `True`, add to any existing expressions.
2368                Otherwise, this resets the expressions.
2369            dialect: the dialect used to parse the input expressions.
2370            copy: if `False`, modify this expression instance in-place.
2371            opts: other options to use to parse the input expressions.
2372
2373        Returns:
2374            Union: the modified expression.
2375        """
2376        this = self.copy() if copy else self
2377        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2378        this.expression.unnest().select(
2379            *expressions, append=append, dialect=dialect, copy=False, **opts
2380        )
2381        return this
2382
2383    @property
2384    def named_selects(self):
2385        return self.this.unnest().named_selects
2386
2387    @property
2388    def is_star(self) -> bool:
2389        return self.this.is_star or self.expression.is_star
2390
2391    @property
2392    def selects(self):
2393        return self.this.unnest().selects
2394
2395    @property
2396    def left(self):
2397        return self.this
2398
2399    @property
2400    def right(self):
2401        return self.expression
2402
2403
2404class Except(Union):
2405    pass
2406
2407
2408class Intersect(Union):
2409    pass
2410
2411
2412class Unnest(UDTF):
2413    arg_types = {
2414        "expressions": True,
2415        "ordinality": False,
2416        "alias": False,
2417        "offset": False,
2418    }
2419
2420
2421class Update(Expression):
2422    arg_types = {
2423        "with": False,
2424        "this": False,
2425        "expressions": True,
2426        "from": False,
2427        "where": False,
2428        "returning": False,
2429        "limit": False,
2430    }
2431
2432
2433class Values(UDTF):
2434    arg_types = {
2435        "expressions": True,
2436        "ordinality": False,
2437        "alias": False,
2438    }
2439
2440
2441class Var(Expression):
2442    pass
2443
2444
2445class Schema(Expression):
2446    arg_types = {"this": False, "expressions": False}
2447
2448
2449# https://dev.mysql.com/doc/refman/8.0/en/select.html
2450# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/SELECT.html
2451class Lock(Expression):
2452    arg_types = {"update": True, "expressions": False, "wait": False}
2453
2454
2455class Select(Subqueryable):
2456    arg_types = {
2457        "with": False,
2458        "kind": False,
2459        "expressions": False,
2460        "hint": False,
2461        "distinct": False,
2462        "into": False,
2463        "from": False,
2464        **QUERY_MODIFIERS,
2465    }
2466
2467    def from_(
2468        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2469    ) -> Select:
2470        """
2471        Set the FROM expression.
2472
2473        Example:
2474            >>> Select().from_("tbl").select("x").sql()
2475            'SELECT x FROM tbl'
2476
2477        Args:
2478            expression : the SQL code strings to parse.
2479                If a `From` instance is passed, this is used as-is.
2480                If another `Expression` instance is passed, it will be wrapped in a `From`.
2481            dialect: the dialect used to parse the input expression.
2482            copy: if `False`, modify this expression instance in-place.
2483            opts: other options to use to parse the input expressions.
2484
2485        Returns:
2486            The modified Select expression.
2487        """
2488        return _apply_builder(
2489            expression=expression,
2490            instance=self,
2491            arg="from",
2492            into=From,
2493            prefix="FROM",
2494            dialect=dialect,
2495            copy=copy,
2496            **opts,
2497        )
2498
2499    def group_by(
2500        self,
2501        *expressions: t.Optional[ExpOrStr],
2502        append: bool = True,
2503        dialect: DialectType = None,
2504        copy: bool = True,
2505        **opts,
2506    ) -> Select:
2507        """
2508        Set the GROUP BY expression.
2509
2510        Example:
2511            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2512            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2513
2514        Args:
2515            *expressions: the SQL code strings to parse.
2516                If a `Group` instance is passed, this is used as-is.
2517                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2518                If nothing is passed in then a group by is not applied to the expression
2519            append: if `True`, add to any existing expressions.
2520                Otherwise, this flattens all the `Group` expression into a single expression.
2521            dialect: the dialect used to parse the input expression.
2522            copy: if `False`, modify this expression instance in-place.
2523            opts: other options to use to parse the input expressions.
2524
2525        Returns:
2526            The modified Select expression.
2527        """
2528        if not expressions:
2529            return self if not copy else self.copy()
2530
2531        return _apply_child_list_builder(
2532            *expressions,
2533            instance=self,
2534            arg="group",
2535            append=append,
2536            copy=copy,
2537            prefix="GROUP BY",
2538            into=Group,
2539            dialect=dialect,
2540            **opts,
2541        )
2542
2543    def order_by(
2544        self,
2545        *expressions: t.Optional[ExpOrStr],
2546        append: bool = True,
2547        dialect: DialectType = None,
2548        copy: bool = True,
2549        **opts,
2550    ) -> Select:
2551        """
2552        Set the ORDER BY expression.
2553
2554        Example:
2555            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2556            'SELECT x FROM tbl ORDER BY x DESC'
2557
2558        Args:
2559            *expressions: the SQL code strings to parse.
2560                If a `Group` instance is passed, this is used as-is.
2561                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2562            append: if `True`, add to any existing expressions.
2563                Otherwise, this flattens all the `Order` expression into a single expression.
2564            dialect: the dialect used to parse the input expression.
2565            copy: if `False`, modify this expression instance in-place.
2566            opts: other options to use to parse the input expressions.
2567
2568        Returns:
2569            The modified Select expression.
2570        """
2571        return _apply_child_list_builder(
2572            *expressions,
2573            instance=self,
2574            arg="order",
2575            append=append,
2576            copy=copy,
2577            prefix="ORDER BY",
2578            into=Order,
2579            dialect=dialect,
2580            **opts,
2581        )
2582
2583    def sort_by(
2584        self,
2585        *expressions: t.Optional[ExpOrStr],
2586        append: bool = True,
2587        dialect: DialectType = None,
2588        copy: bool = True,
2589        **opts,
2590    ) -> Select:
2591        """
2592        Set the SORT BY expression.
2593
2594        Example:
2595            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2596            'SELECT x FROM tbl SORT BY x DESC'
2597
2598        Args:
2599            *expressions: the SQL code strings to parse.
2600                If a `Group` instance is passed, this is used as-is.
2601                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2602            append: if `True`, add to any existing expressions.
2603                Otherwise, this flattens all the `Order` expression into a single expression.
2604            dialect: the dialect used to parse the input expression.
2605            copy: if `False`, modify this expression instance in-place.
2606            opts: other options to use to parse the input expressions.
2607
2608        Returns:
2609            The modified Select expression.
2610        """
2611        return _apply_child_list_builder(
2612            *expressions,
2613            instance=self,
2614            arg="sort",
2615            append=append,
2616            copy=copy,
2617            prefix="SORT BY",
2618            into=Sort,
2619            dialect=dialect,
2620            **opts,
2621        )
2622
2623    def cluster_by(
2624        self,
2625        *expressions: t.Optional[ExpOrStr],
2626        append: bool = True,
2627        dialect: DialectType = None,
2628        copy: bool = True,
2629        **opts,
2630    ) -> Select:
2631        """
2632        Set the CLUSTER BY expression.
2633
2634        Example:
2635            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2636            'SELECT x FROM tbl CLUSTER BY x DESC'
2637
2638        Args:
2639            *expressions: the SQL code strings to parse.
2640                If a `Group` instance is passed, this is used as-is.
2641                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2642            append: if `True`, add to any existing expressions.
2643                Otherwise, this flattens all the `Order` expression into a single expression.
2644            dialect: the dialect used to parse the input expression.
2645            copy: if `False`, modify this expression instance in-place.
2646            opts: other options to use to parse the input expressions.
2647
2648        Returns:
2649            The modified Select expression.
2650        """
2651        return _apply_child_list_builder(
2652            *expressions,
2653            instance=self,
2654            arg="cluster",
2655            append=append,
2656            copy=copy,
2657            prefix="CLUSTER BY",
2658            into=Cluster,
2659            dialect=dialect,
2660            **opts,
2661        )
2662
2663    def limit(
2664        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2665    ) -> Select:
2666        """
2667        Set the LIMIT expression.
2668
2669        Example:
2670            >>> Select().from_("tbl").select("x").limit(10).sql()
2671            'SELECT x FROM tbl LIMIT 10'
2672
2673        Args:
2674            expression: the SQL code string to parse.
2675                This can also be an integer.
2676                If a `Limit` instance is passed, this is used as-is.
2677                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2678            dialect: the dialect used to parse the input expression.
2679            copy: if `False`, modify this expression instance in-place.
2680            opts: other options to use to parse the input expressions.
2681
2682        Returns:
2683            Select: the modified expression.
2684        """
2685        return _apply_builder(
2686            expression=expression,
2687            instance=self,
2688            arg="limit",
2689            into=Limit,
2690            prefix="LIMIT",
2691            dialect=dialect,
2692            copy=copy,
2693            **opts,
2694        )
2695
2696    def offset(
2697        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2698    ) -> Select:
2699        """
2700        Set the OFFSET expression.
2701
2702        Example:
2703            >>> Select().from_("tbl").select("x").offset(10).sql()
2704            'SELECT x FROM tbl OFFSET 10'
2705
2706        Args:
2707            expression: the SQL code string to parse.
2708                This can also be an integer.
2709                If a `Offset` instance is passed, this is used as-is.
2710                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2711            dialect: the dialect used to parse the input expression.
2712            copy: if `False`, modify this expression instance in-place.
2713            opts: other options to use to parse the input expressions.
2714
2715        Returns:
2716            The modified Select expression.
2717        """
2718        return _apply_builder(
2719            expression=expression,
2720            instance=self,
2721            arg="offset",
2722            into=Offset,
2723            prefix="OFFSET",
2724            dialect=dialect,
2725            copy=copy,
2726            **opts,
2727        )
2728
2729    def select(
2730        self,
2731        *expressions: t.Optional[ExpOrStr],
2732        append: bool = True,
2733        dialect: DialectType = None,
2734        copy: bool = True,
2735        **opts,
2736    ) -> Select:
2737        """
2738        Append to or set the SELECT expressions.
2739
2740        Example:
2741            >>> Select().select("x", "y").sql()
2742            'SELECT x, y'
2743
2744        Args:
2745            *expressions: the SQL code strings to parse.
2746                If an `Expression` instance is passed, it will be used as-is.
2747            append: if `True`, add to any existing expressions.
2748                Otherwise, this resets the expressions.
2749            dialect: the dialect used to parse the input expressions.
2750            copy: if `False`, modify this expression instance in-place.
2751            opts: other options to use to parse the input expressions.
2752
2753        Returns:
2754            The modified Select expression.
2755        """
2756        return _apply_list_builder(
2757            *expressions,
2758            instance=self,
2759            arg="expressions",
2760            append=append,
2761            dialect=dialect,
2762            copy=copy,
2763            **opts,
2764        )
2765
2766    def lateral(
2767        self,
2768        *expressions: t.Optional[ExpOrStr],
2769        append: bool = True,
2770        dialect: DialectType = None,
2771        copy: bool = True,
2772        **opts,
2773    ) -> Select:
2774        """
2775        Append to or set the LATERAL expressions.
2776
2777        Example:
2778            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2779            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2780
2781        Args:
2782            *expressions: the SQL code strings to parse.
2783                If an `Expression` instance is passed, it will be used as-is.
2784            append: if `True`, add to any existing expressions.
2785                Otherwise, this resets the expressions.
2786            dialect: the dialect used to parse the input expressions.
2787            copy: if `False`, modify this expression instance in-place.
2788            opts: other options to use to parse the input expressions.
2789
2790        Returns:
2791            The modified Select expression.
2792        """
2793        return _apply_list_builder(
2794            *expressions,
2795            instance=self,
2796            arg="laterals",
2797            append=append,
2798            into=Lateral,
2799            prefix="LATERAL VIEW",
2800            dialect=dialect,
2801            copy=copy,
2802            **opts,
2803        )
2804
2805    def join(
2806        self,
2807        expression: ExpOrStr,
2808        on: t.Optional[ExpOrStr] = None,
2809        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2810        append: bool = True,
2811        join_type: t.Optional[str] = None,
2812        join_alias: t.Optional[Identifier | str] = None,
2813        dialect: DialectType = None,
2814        copy: bool = True,
2815        **opts,
2816    ) -> Select:
2817        """
2818        Append to or set the JOIN expressions.
2819
2820        Example:
2821            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2822            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2823
2824            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2825            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2826
2827            Use `join_type` to change the type of join:
2828
2829            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2830            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2831
2832        Args:
2833            expression: the SQL code string to parse.
2834                If an `Expression` instance is passed, it will be used as-is.
2835            on: optionally specify the join "on" criteria as a SQL string.
2836                If an `Expression` instance is passed, it will be used as-is.
2837            using: optionally specify the join "using" criteria as a SQL string.
2838                If an `Expression` instance is passed, it will be used as-is.
2839            append: if `True`, add to any existing expressions.
2840                Otherwise, this resets the expressions.
2841            join_type: if set, alter the parsed join type.
2842            join_alias: an optional alias for the joined source.
2843            dialect: the dialect used to parse the input expressions.
2844            copy: if `False`, modify this expression instance in-place.
2845            opts: other options to use to parse the input expressions.
2846
2847        Returns:
2848            Select: the modified expression.
2849        """
2850        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2851
2852        try:
2853            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2854        except ParseError:
2855            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2856
2857        join = expression if isinstance(expression, Join) else Join(this=expression)
2858
2859        if isinstance(join.this, Select):
2860            join.this.replace(join.this.subquery())
2861
2862        if join_type:
2863            method: t.Optional[Token]
2864            side: t.Optional[Token]
2865            kind: t.Optional[Token]
2866
2867            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2868
2869            if method:
2870                join.set("method", method.text)
2871            if side:
2872                join.set("side", side.text)
2873            if kind:
2874                join.set("kind", kind.text)
2875
2876        if on:
2877            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2878            join.set("on", on)
2879
2880        if using:
2881            join = _apply_list_builder(
2882                *ensure_list(using),
2883                instance=join,
2884                arg="using",
2885                append=append,
2886                copy=copy,
2887                **opts,
2888            )
2889
2890        if join_alias:
2891            join.set("this", alias_(join.this, join_alias, table=True))
2892
2893        return _apply_list_builder(
2894            join,
2895            instance=self,
2896            arg="joins",
2897            append=append,
2898            copy=copy,
2899            **opts,
2900        )
2901
2902    def where(
2903        self,
2904        *expressions: t.Optional[ExpOrStr],
2905        append: bool = True,
2906        dialect: DialectType = None,
2907        copy: bool = True,
2908        **opts,
2909    ) -> Select:
2910        """
2911        Append to or set the WHERE expressions.
2912
2913        Example:
2914            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2915            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2916
2917        Args:
2918            *expressions: the SQL code strings to parse.
2919                If an `Expression` instance is passed, it will be used as-is.
2920                Multiple expressions are combined with an AND operator.
2921            append: if `True`, AND the new expressions to any existing expression.
2922                Otherwise, this resets the expression.
2923            dialect: the dialect used to parse the input expressions.
2924            copy: if `False`, modify this expression instance in-place.
2925            opts: other options to use to parse the input expressions.
2926
2927        Returns:
2928            Select: the modified expression.
2929        """
2930        return _apply_conjunction_builder(
2931            *expressions,
2932            instance=self,
2933            arg="where",
2934            append=append,
2935            into=Where,
2936            dialect=dialect,
2937            copy=copy,
2938            **opts,
2939        )
2940
2941    def having(
2942        self,
2943        *expressions: t.Optional[ExpOrStr],
2944        append: bool = True,
2945        dialect: DialectType = None,
2946        copy: bool = True,
2947        **opts,
2948    ) -> Select:
2949        """
2950        Append to or set the HAVING expressions.
2951
2952        Example:
2953            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2954            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2955
2956        Args:
2957            *expressions: the SQL code strings to parse.
2958                If an `Expression` instance is passed, it will be used as-is.
2959                Multiple expressions are combined with an AND operator.
2960            append: if `True`, AND the new expressions to any existing expression.
2961                Otherwise, this resets the expression.
2962            dialect: the dialect used to parse the input expressions.
2963            copy: if `False`, modify this expression instance in-place.
2964            opts: other options to use to parse the input expressions.
2965
2966        Returns:
2967            The modified Select expression.
2968        """
2969        return _apply_conjunction_builder(
2970            *expressions,
2971            instance=self,
2972            arg="having",
2973            append=append,
2974            into=Having,
2975            dialect=dialect,
2976            copy=copy,
2977            **opts,
2978        )
2979
2980    def window(
2981        self,
2982        *expressions: t.Optional[ExpOrStr],
2983        append: bool = True,
2984        dialect: DialectType = None,
2985        copy: bool = True,
2986        **opts,
2987    ) -> Select:
2988        return _apply_list_builder(
2989            *expressions,
2990            instance=self,
2991            arg="windows",
2992            append=append,
2993            into=Window,
2994            dialect=dialect,
2995            copy=copy,
2996            **opts,
2997        )
2998
2999    def qualify(
3000        self,
3001        *expressions: t.Optional[ExpOrStr],
3002        append: bool = True,
3003        dialect: DialectType = None,
3004        copy: bool = True,
3005        **opts,
3006    ) -> Select:
3007        return _apply_conjunction_builder(
3008            *expressions,
3009            instance=self,
3010            arg="qualify",
3011            append=append,
3012            into=Qualify,
3013            dialect=dialect,
3014            copy=copy,
3015            **opts,
3016        )
3017
3018    def distinct(
3019        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3020    ) -> Select:
3021        """
3022        Set the OFFSET expression.
3023
3024        Example:
3025            >>> Select().from_("tbl").select("x").distinct().sql()
3026            'SELECT DISTINCT x FROM tbl'
3027
3028        Args:
3029            ons: the expressions to distinct on
3030            distinct: whether the Select should be distinct
3031            copy: if `False`, modify this expression instance in-place.
3032
3033        Returns:
3034            Select: the modified expression.
3035        """
3036        instance = _maybe_copy(self, copy)
3037        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3038        instance.set("distinct", Distinct(on=on) if distinct else None)
3039        return instance
3040
3041    def ctas(
3042        self,
3043        table: ExpOrStr,
3044        properties: t.Optional[t.Dict] = None,
3045        dialect: DialectType = None,
3046        copy: bool = True,
3047        **opts,
3048    ) -> Create:
3049        """
3050        Convert this expression to a CREATE TABLE AS statement.
3051
3052        Example:
3053            >>> Select().select("*").from_("tbl").ctas("x").sql()
3054            'CREATE TABLE x AS SELECT * FROM tbl'
3055
3056        Args:
3057            table: the SQL code string to parse as the table name.
3058                If another `Expression` instance is passed, it will be used as-is.
3059            properties: an optional mapping of table properties
3060            dialect: the dialect used to parse the input table.
3061            copy: if `False`, modify this expression instance in-place.
3062            opts: other options to use to parse the input table.
3063
3064        Returns:
3065            The new Create expression.
3066        """
3067        instance = _maybe_copy(self, copy)
3068        table_expression = maybe_parse(
3069            table,
3070            into=Table,
3071            dialect=dialect,
3072            **opts,
3073        )
3074        properties_expression = None
3075        if properties:
3076            properties_expression = Properties.from_dict(properties)
3077
3078        return Create(
3079            this=table_expression,
3080            kind="table",
3081            expression=instance,
3082            properties=properties_expression,
3083        )
3084
3085    def lock(self, update: bool = True, copy: bool = True) -> Select:
3086        """
3087        Set the locking read mode for this expression.
3088
3089        Examples:
3090            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3091            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3092
3093            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3094            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3095
3096        Args:
3097            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3098            copy: if `False`, modify this expression instance in-place.
3099
3100        Returns:
3101            The modified expression.
3102        """
3103        inst = _maybe_copy(self, copy)
3104        inst.set("locks", [Lock(update=update)])
3105
3106        return inst
3107
3108    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3109        """
3110        Set hints for this expression.
3111
3112        Examples:
3113            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3114            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3115
3116        Args:
3117            hints: The SQL code strings to parse as the hints.
3118                If an `Expression` instance is passed, it will be used as-is.
3119            dialect: The dialect used to parse the hints.
3120            copy: If `False`, modify this expression instance in-place.
3121
3122        Returns:
3123            The modified expression.
3124        """
3125        inst = _maybe_copy(self, copy)
3126        inst.set(
3127            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3128        )
3129
3130        return inst
3131
3132    @property
3133    def named_selects(self) -> t.List[str]:
3134        return [e.output_name for e in self.expressions if e.alias_or_name]
3135
3136    @property
3137    def is_star(self) -> bool:
3138        return any(expression.is_star for expression in self.expressions)
3139
3140    @property
3141    def selects(self) -> t.List[Expression]:
3142        return self.expressions
3143
3144
3145class Subquery(DerivedTable, Unionable):
3146    arg_types = {
3147        "this": True,
3148        "alias": False,
3149        "with": False,
3150        **QUERY_MODIFIERS,
3151    }
3152
3153    def unnest(self):
3154        """
3155        Returns the first non subquery.
3156        """
3157        expression = self
3158        while isinstance(expression, Subquery):
3159            expression = expression.this
3160        return expression
3161
3162    @property
3163    def is_star(self) -> bool:
3164        return self.this.is_star
3165
3166    @property
3167    def output_name(self) -> str:
3168        return self.alias
3169
3170
3171class TableSample(Expression):
3172    arg_types = {
3173        "this": False,
3174        "method": False,
3175        "bucket_numerator": False,
3176        "bucket_denominator": False,
3177        "bucket_field": False,
3178        "percent": False,
3179        "rows": False,
3180        "size": False,
3181        "seed": False,
3182        "kind": False,
3183    }
3184
3185
3186class Tag(Expression):
3187    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3188
3189    arg_types = {
3190        "this": False,
3191        "prefix": False,
3192        "postfix": False,
3193    }
3194
3195
3196# Represents both the standard SQL PIVOT operator and DuckDB's "simplified" PIVOT syntax
3197# https://duckdb.org/docs/sql/statements/pivot
3198class Pivot(Expression):
3199    arg_types = {
3200        "this": False,
3201        "alias": False,
3202        "expressions": True,
3203        "field": False,
3204        "unpivot": False,
3205        "using": False,
3206        "group": False,
3207        "columns": False,
3208    }
3209
3210
3211class Window(Expression):
3212    arg_types = {
3213        "this": True,
3214        "partition_by": False,
3215        "order": False,
3216        "spec": False,
3217        "alias": False,
3218        "over": False,
3219        "first": False,
3220    }
3221
3222
3223class WindowSpec(Expression):
3224    arg_types = {
3225        "kind": False,
3226        "start": False,
3227        "start_side": False,
3228        "end": False,
3229        "end_side": False,
3230    }
3231
3232
3233class Where(Expression):
3234    pass
3235
3236
3237class Star(Expression):
3238    arg_types = {"except": False, "replace": False}
3239
3240    @property
3241    def name(self) -> str:
3242        return "*"
3243
3244    @property
3245    def output_name(self) -> str:
3246        return self.name
3247
3248
3249class Parameter(Condition):
3250    arg_types = {"this": True, "wrapped": False}
3251
3252
3253class SessionParameter(Condition):
3254    arg_types = {"this": True, "kind": False}
3255
3256
3257class Placeholder(Condition):
3258    arg_types = {"this": False, "kind": False}
3259
3260
3261class Null(Condition):
3262    arg_types: t.Dict[str, t.Any] = {}
3263
3264    @property
3265    def name(self) -> str:
3266        return "NULL"
3267
3268
3269class Boolean(Condition):
3270    pass
3271
3272
3273class DataTypeSize(Expression):
3274    arg_types = {"this": True, "expression": False}
3275
3276
3277class DataType(Expression):
3278    arg_types = {
3279        "this": True,
3280        "expressions": False,
3281        "nested": False,
3282        "values": False,
3283        "prefix": False,
3284    }
3285
3286    class Type(AutoName):
3287        ARRAY = auto()
3288        BIGDECIMAL = auto()
3289        BIGINT = auto()
3290        BIGSERIAL = auto()
3291        BINARY = auto()
3292        BIT = auto()
3293        BOOLEAN = auto()
3294        CHAR = auto()
3295        DATE = auto()
3296        DATETIME = auto()
3297        DATETIME64 = auto()
3298        ENUM = auto()
3299        INT4RANGE = auto()
3300        INT4MULTIRANGE = auto()
3301        INT8RANGE = auto()
3302        INT8MULTIRANGE = auto()
3303        NUMRANGE = auto()
3304        NUMMULTIRANGE = auto()
3305        TSRANGE = auto()
3306        TSMULTIRANGE = auto()
3307        TSTZRANGE = auto()
3308        TSTZMULTIRANGE = auto()
3309        DATERANGE = auto()
3310        DATEMULTIRANGE = auto()
3311        DECIMAL = auto()
3312        DOUBLE = auto()
3313        FLOAT = auto()
3314        GEOGRAPHY = auto()
3315        GEOMETRY = auto()
3316        HLLSKETCH = auto()
3317        HSTORE = auto()
3318        IMAGE = auto()
3319        INET = auto()
3320        INT = auto()
3321        INT128 = auto()
3322        INT256 = auto()
3323        INTERVAL = auto()
3324        JSON = auto()
3325        JSONB = auto()
3326        LONGBLOB = auto()
3327        LONGTEXT = auto()
3328        MAP = auto()
3329        MEDIUMBLOB = auto()
3330        MEDIUMTEXT = auto()
3331        MONEY = auto()
3332        NCHAR = auto()
3333        NULL = auto()
3334        NULLABLE = auto()
3335        NVARCHAR = auto()
3336        OBJECT = auto()
3337        ROWVERSION = auto()
3338        SERIAL = auto()
3339        SET = auto()
3340        SMALLINT = auto()
3341        SMALLMONEY = auto()
3342        SMALLSERIAL = auto()
3343        STRUCT = auto()
3344        SUPER = auto()
3345        TEXT = auto()
3346        TIME = auto()
3347        TIMESTAMP = auto()
3348        TIMESTAMPTZ = auto()
3349        TIMESTAMPLTZ = auto()
3350        TINYINT = auto()
3351        UBIGINT = auto()
3352        UINT = auto()
3353        USMALLINT = auto()
3354        UTINYINT = auto()
3355        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3356        UINT128 = auto()
3357        UINT256 = auto()
3358        UNIQUEIDENTIFIER = auto()
3359        USERDEFINED = "USER-DEFINED"
3360        UUID = auto()
3361        VARBINARY = auto()
3362        VARCHAR = auto()
3363        VARIANT = auto()
3364        XML = auto()
3365
3366    TEXT_TYPES = {
3367        Type.CHAR,
3368        Type.NCHAR,
3369        Type.VARCHAR,
3370        Type.NVARCHAR,
3371        Type.TEXT,
3372    }
3373
3374    INTEGER_TYPES = {
3375        Type.INT,
3376        Type.TINYINT,
3377        Type.SMALLINT,
3378        Type.BIGINT,
3379        Type.INT128,
3380        Type.INT256,
3381    }
3382
3383    FLOAT_TYPES = {
3384        Type.FLOAT,
3385        Type.DOUBLE,
3386    }
3387
3388    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3389
3390    TEMPORAL_TYPES = {
3391        Type.TIME,
3392        Type.TIMESTAMP,
3393        Type.TIMESTAMPTZ,
3394        Type.TIMESTAMPLTZ,
3395        Type.DATE,
3396        Type.DATETIME,
3397        Type.DATETIME64,
3398    }
3399
3400    META_TYPES = {"UNKNOWN", "NULL"}
3401
3402    @classmethod
3403    def build(
3404        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3405    ) -> DataType:
3406        from sqlglot import parse_one
3407
3408        if isinstance(dtype, str):
3409            upper = dtype.upper()
3410            if upper in DataType.META_TYPES:
3411                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3412            else:
3413                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3414
3415            if data_type_exp is None:
3416                raise ValueError(f"Unparsable data type value: {dtype}")
3417        elif isinstance(dtype, DataType.Type):
3418            data_type_exp = DataType(this=dtype)
3419        elif isinstance(dtype, DataType):
3420            return dtype
3421        else:
3422            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3423
3424        return DataType(**{**data_type_exp.args, **kwargs})
3425
3426    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3427        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
3428
3429
3430# https://www.postgresql.org/docs/15/datatype-pseudo.html
3431class PseudoType(Expression):
3432    pass
3433
3434
3435# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...)
3436class SubqueryPredicate(Predicate):
3437    pass
3438
3439
3440class All(SubqueryPredicate):
3441    pass
3442
3443
3444class Any(SubqueryPredicate):
3445    pass
3446
3447
3448class Exists(SubqueryPredicate):
3449    pass
3450
3451
3452# Commands to interact with the databases or engines. For most of the command
3453# expressions we parse whatever comes after the command's name as a string.
3454class Command(Expression):
3455    arg_types = {"this": True, "expression": False}
3456
3457
3458class Transaction(Expression):
3459    arg_types = {"this": False, "modes": False}
3460
3461
3462class Commit(Expression):
3463    arg_types = {"chain": False}
3464
3465
3466class Rollback(Expression):
3467    arg_types = {"savepoint": False}
3468
3469
3470class AlterTable(Expression):
3471    arg_types = {"this": True, "actions": True, "exists": False}
3472
3473
3474class AddConstraint(Expression):
3475    arg_types = {"this": False, "expression": False, "enforced": False}
3476
3477
3478class DropPartition(Expression):
3479    arg_types = {"expressions": True, "exists": False}
3480
3481
3482# Binary expressions like (ADD a b)
3483class Binary(Condition):
3484    arg_types = {"this": True, "expression": True}
3485
3486    @property
3487    def left(self):
3488        return self.this
3489
3490    @property
3491    def right(self):
3492        return self.expression
3493
3494
3495class Add(Binary):
3496    pass
3497
3498
3499class Connector(Binary):
3500    pass
3501
3502
3503class And(Connector):
3504    pass
3505
3506
3507class Or(Connector):
3508    pass
3509
3510
3511class BitwiseAnd(Binary):
3512    pass
3513
3514
3515class BitwiseLeftShift(Binary):
3516    pass
3517
3518
3519class BitwiseOr(Binary):
3520    pass
3521
3522
3523class BitwiseRightShift(Binary):
3524    pass
3525
3526
3527class BitwiseXor(Binary):
3528    pass
3529
3530
3531class Div(Binary):
3532    pass
3533
3534
3535class Overlaps(Binary):
3536    pass
3537
3538
3539class Dot(Binary):
3540    @property
3541    def name(self) -> str:
3542        return self.expression.name
3543
3544    @property
3545    def output_name(self) -> str:
3546        return self.name
3547
3548    @classmethod
3549    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3550        """Build a Dot object with a sequence of expressions."""
3551        if len(expressions) < 2:
3552            raise ValueError(f"Dot requires >= 2 expressions.")
3553
3554        a, b, *expressions = expressions
3555        dot = Dot(this=a, expression=b)
3556
3557        for expression in expressions:
3558            dot = Dot(this=dot, expression=expression)
3559
3560        return dot
3561
3562
3563class DPipe(Binary):
3564    pass
3565
3566
3567class SafeDPipe(DPipe):
3568    pass
3569
3570
3571class EQ(Binary, Predicate):
3572    pass
3573
3574
3575class NullSafeEQ(Binary, Predicate):
3576    pass
3577
3578
3579class NullSafeNEQ(Binary, Predicate):
3580    pass
3581
3582
3583class Distance(Binary):
3584    pass
3585
3586
3587class Escape(Binary):
3588    pass
3589
3590
3591class Glob(Binary, Predicate):
3592    pass
3593
3594
3595class GT(Binary, Predicate):
3596    pass
3597
3598
3599class GTE(Binary, Predicate):
3600    pass
3601
3602
3603class ILike(Binary, Predicate):
3604    pass
3605
3606
3607class ILikeAny(Binary, Predicate):
3608    pass
3609
3610
3611class IntDiv(Binary):
3612    pass
3613
3614
3615class Is(Binary, Predicate):
3616    pass
3617
3618
3619class Kwarg(Binary):
3620    """Kwarg in special functions like func(kwarg => y)."""
3621
3622
3623class Like(Binary, Predicate):
3624    pass
3625
3626
3627class LikeAny(Binary, Predicate):
3628    pass
3629
3630
3631class LT(Binary, Predicate):
3632    pass
3633
3634
3635class LTE(Binary, Predicate):
3636    pass
3637
3638
3639class Mod(Binary):
3640    pass
3641
3642
3643class Mul(Binary):
3644    pass
3645
3646
3647class NEQ(Binary, Predicate):
3648    pass
3649
3650
3651class SimilarTo(Binary, Predicate):
3652    pass
3653
3654
3655class Slice(Binary):
3656    arg_types = {"this": False, "expression": False}
3657
3658
3659class Sub(Binary):
3660    pass
3661
3662
3663class ArrayOverlaps(Binary):
3664    pass
3665
3666
3667# Unary Expressions
3668# (NOT a)
3669class Unary(Condition):
3670    pass
3671
3672
3673class BitwiseNot(Unary):
3674    pass
3675
3676
3677class Not(Unary):
3678    pass
3679
3680
3681class Paren(Unary):
3682    arg_types = {"this": True, "with": False}
3683
3684    @property
3685    def output_name(self) -> str:
3686        return self.this.name
3687
3688
3689class Neg(Unary):
3690    pass
3691
3692
3693class Alias(Expression):
3694    arg_types = {"this": True, "alias": False}
3695
3696    @property
3697    def output_name(self) -> str:
3698        return self.alias
3699
3700
3701class Aliases(Expression):
3702    arg_types = {"this": True, "expressions": True}
3703
3704    @property
3705    def aliases(self):
3706        return self.expressions
3707
3708
3709class AtTimeZone(Expression):
3710    arg_types = {"this": True, "zone": True}
3711
3712
3713class Between(Predicate):
3714    arg_types = {"this": True, "low": True, "high": True}
3715
3716
3717class Bracket(Condition):
3718    arg_types = {"this": True, "expressions": True}
3719
3720
3721class SafeBracket(Bracket):
3722    """Represents array lookup where OOB index yields NULL instead of causing a failure."""
3723
3724
3725class Distinct(Expression):
3726    arg_types = {"expressions": False, "on": False}
3727
3728
3729class In(Predicate):
3730    arg_types = {
3731        "this": True,
3732        "expressions": False,
3733        "query": False,
3734        "unnest": False,
3735        "field": False,
3736        "is_global": False,
3737    }
3738
3739
3740class TimeUnit(Expression):
3741    """Automatically converts unit arg into a var."""
3742
3743    arg_types = {"unit": False}
3744
3745    def __init__(self, **args):
3746        unit = args.get("unit")
3747        if isinstance(unit, (Column, Literal)):
3748            args["unit"] = Var(this=unit.name)
3749        elif isinstance(unit, Week):
3750            unit.set("this", Var(this=unit.this.name))
3751
3752        super().__init__(**args)
3753
3754
3755class Interval(TimeUnit):
3756    arg_types = {"this": False, "unit": False}
3757
3758    @property
3759    def unit(self) -> t.Optional[Var]:
3760        return self.args.get("unit")
3761
3762
3763class IgnoreNulls(Expression):
3764    pass
3765
3766
3767class RespectNulls(Expression):
3768    pass
3769
3770
3771# Functions
3772class Func(Condition):
3773    """
3774    The base class for all function expressions.
3775
3776    Attributes:
3777        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3778            treated as a variable length argument and the argument's value will be stored as a list.
3779        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3780            for this function expression. These values are used to map this node to a name during parsing
3781            as well as to provide the function's name during SQL string generation. By default the SQL
3782            name is set to the expression's class name transformed to snake case.
3783    """
3784
3785    is_var_len_args = False
3786
3787    @classmethod
3788    def from_arg_list(cls, args):
3789        if cls.is_var_len_args:
3790            all_arg_keys = list(cls.arg_types)
3791            # If this function supports variable length argument treat the last argument as such.
3792            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3793            num_non_var = len(non_var_len_arg_keys)
3794
3795            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3796            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3797        else:
3798            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3799
3800        return cls(**args_dict)
3801
3802    @classmethod
3803    def sql_names(cls):
3804        if cls is Func:
3805            raise NotImplementedError(
3806                "SQL name is only supported by concrete function implementations"
3807            )
3808        if "_sql_names" not in cls.__dict__:
3809            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3810        return cls._sql_names
3811
3812    @classmethod
3813    def sql_name(cls):
3814        return cls.sql_names()[0]
3815
3816    @classmethod
3817    def default_parser_mappings(cls):
3818        return {name: cls.from_arg_list for name in cls.sql_names()}
3819
3820
3821class AggFunc(Func):
3822    pass
3823
3824
3825class ParameterizedAgg(AggFunc):
3826    arg_types = {"this": True, "expressions": True, "params": True}
3827
3828
3829class Abs(Func):
3830    pass
3831
3832
3833class Anonymous(Func):
3834    arg_types = {"this": True, "expressions": False}
3835    is_var_len_args = True
3836
3837
3838# https://docs.snowflake.com/en/sql-reference/functions/hll
3839# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html
3840class Hll(AggFunc):
3841    arg_types = {"this": True, "expressions": False}
3842    is_var_len_args = True
3843
3844
3845class ApproxDistinct(AggFunc):
3846    arg_types = {"this": True, "accuracy": False}
3847    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
3848
3849
3850class Array(Func):
3851    arg_types = {"expressions": False}
3852    is_var_len_args = True
3853
3854
3855# https://docs.snowflake.com/en/sql-reference/functions/to_char
3856class ToChar(Func):
3857    arg_types = {"this": True, "format": False}
3858
3859
3860class GenerateSeries(Func):
3861    arg_types = {"start": True, "end": True, "step": False}
3862
3863
3864class ArrayAgg(AggFunc):
3865    pass
3866
3867
3868class ArrayAll(Func):
3869    arg_types = {"this": True, "expression": True}
3870
3871
3872class ArrayAny(Func):
3873    arg_types = {"this": True, "expression": True}
3874
3875
3876class ArrayConcat(Func):
3877    arg_types = {"this": True, "expressions": False}
3878    is_var_len_args = True
3879
3880
3881class ArrayContains(Binary, Func):
3882    pass
3883
3884
3885class ArrayContained(Binary):
3886    pass
3887
3888
3889class ArrayFilter(Func):
3890    arg_types = {"this": True, "expression": True}
3891    _sql_names = ["FILTER", "ARRAY_FILTER"]
3892
3893
3894class ArrayJoin(Func):
3895    arg_types = {"this": True, "expression": True, "null": False}
3896
3897
3898class ArraySize(Func):
3899    arg_types = {"this": True, "expression": False}
3900
3901
3902class ArraySort(Func):
3903    arg_types = {"this": True, "expression": False}
3904
3905
3906class ArraySum(Func):
3907    pass
3908
3909
3910class ArrayUnionAgg(AggFunc):
3911    pass
3912
3913
3914class Avg(AggFunc):
3915    pass
3916
3917
3918class AnyValue(AggFunc):
3919    pass
3920
3921
3922class Case(Func):
3923    arg_types = {"this": False, "ifs": True, "default": False}
3924
3925    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3926        instance = _maybe_copy(self, copy)
3927        instance.append(
3928            "ifs",
3929            If(
3930                this=maybe_parse(condition, copy=copy, **opts),
3931                true=maybe_parse(then, copy=copy, **opts),
3932            ),
3933        )
3934        return instance
3935
3936    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3937        instance = _maybe_copy(self, copy)
3938        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3939        return instance
3940
3941
3942class Cast(Func):
3943    arg_types = {"this": True, "to": True}
3944
3945    @property
3946    def name(self) -> str:
3947        return self.this.name
3948
3949    @property
3950    def to(self) -> DataType:
3951        return self.args["to"]
3952
3953    @property
3954    def output_name(self) -> str:
3955        return self.name
3956
3957    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3958        return self.to.is_type(*dtypes)
3959
3960
3961class CastToStrType(Func):
3962    arg_types = {"this": True, "expression": True}
3963
3964
3965class Collate(Binary):
3966    pass
3967
3968
3969class TryCast(Cast):
3970    pass
3971
3972
3973class Ceil(Func):
3974    arg_types = {"this": True, "decimals": False}
3975    _sql_names = ["CEIL", "CEILING"]
3976
3977
3978class Coalesce(Func):
3979    arg_types = {"this": True, "expressions": False}
3980    is_var_len_args = True
3981    _sql_names = ["COALESCE", "IFNULL", "NVL"]
3982
3983
3984class Concat(Func):
3985    arg_types = {"expressions": True}
3986    is_var_len_args = True
3987
3988
3989class SafeConcat(Concat):
3990    pass
3991
3992
3993class ConcatWs(Concat):
3994    _sql_names = ["CONCAT_WS"]
3995
3996
3997class Count(AggFunc):
3998    arg_types = {"this": False, "expressions": False}
3999    is_var_len_args = True
4000
4001
4002class CountIf(AggFunc):
4003    pass
4004
4005
4006class CurrentDate(Func):
4007    arg_types = {"this": False}
4008
4009
4010class CurrentDatetime(Func):
4011    arg_types = {"this": False}
4012
4013
4014class CurrentTime(Func):
4015    arg_types = {"this": False}
4016
4017
4018class CurrentTimestamp(Func):
4019    arg_types = {"this": False}
4020
4021
4022class CurrentUser(Func):
4023    arg_types = {"this": False}
4024
4025
4026class DateAdd(Func, TimeUnit):
4027    arg_types = {"this": True, "expression": True, "unit": False}
4028
4029
4030class DateSub(Func, TimeUnit):
4031    arg_types = {"this": True, "expression": True, "unit": False}
4032
4033
4034class DateDiff(Func, TimeUnit):
4035    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4036    arg_types = {"this": True, "expression": True, "unit": False}
4037
4038
4039class DateTrunc(Func):
4040    arg_types = {"unit": True, "this": True, "zone": False}
4041
4042
4043class DatetimeAdd(Func, TimeUnit):
4044    arg_types = {"this": True, "expression": True, "unit": False}
4045
4046
4047class DatetimeSub(Func, TimeUnit):
4048    arg_types = {"this": True, "expression": True, "unit": False}
4049
4050
4051class DatetimeDiff(Func, TimeUnit):
4052    arg_types = {"this": True, "expression": True, "unit": False}
4053
4054
4055class DatetimeTrunc(Func, TimeUnit):
4056    arg_types = {"this": True, "unit": True, "zone": False}
4057
4058
4059class DayOfWeek(Func):
4060    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
4061
4062
4063class DayOfMonth(Func):
4064    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
4065
4066
4067class DayOfYear(Func):
4068    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
4069
4070
4071class WeekOfYear(Func):
4072    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
4073
4074
4075class LastDateOfMonth(Func):
4076    pass
4077
4078
4079class Extract(Func):
4080    arg_types = {"this": True, "expression": True}
4081
4082
4083class TimestampAdd(Func, TimeUnit):
4084    arg_types = {"this": True, "expression": True, "unit": False}
4085
4086
4087class TimestampSub(Func, TimeUnit):
4088    arg_types = {"this": True, "expression": True, "unit": False}
4089
4090
4091class TimestampDiff(Func, TimeUnit):
4092    arg_types = {"this": True, "expression": True, "unit": False}
4093
4094
4095class TimestampTrunc(Func, TimeUnit):
4096    arg_types = {"this": True, "unit": True, "zone": False}
4097
4098
4099class TimeAdd(Func, TimeUnit):
4100    arg_types = {"this": True, "expression": True, "unit": False}
4101
4102
4103class TimeSub(Func, TimeUnit):
4104    arg_types = {"this": True, "expression": True, "unit": False}
4105
4106
4107class TimeDiff(Func, TimeUnit):
4108    arg_types = {"this": True, "expression": True, "unit": False}
4109
4110
4111class TimeTrunc(Func, TimeUnit):
4112    arg_types = {"this": True, "unit": True, "zone": False}
4113
4114
4115class DateFromParts(Func):
4116    _sql_names = ["DATEFROMPARTS"]
4117    arg_types = {"year": True, "month": True, "day": True}
4118
4119
4120class DateStrToDate(Func):
4121    pass
4122
4123
4124class DateToDateStr(Func):
4125    pass
4126
4127
4128class DateToDi(Func):
4129    pass
4130
4131
4132class Date(Func):
4133    arg_types = {"expressions": True}
4134    is_var_len_args = True
4135
4136
4137class Day(Func):
4138    pass
4139
4140
4141class Decode(Func):
4142    arg_types = {"this": True, "charset": True, "replace": False}
4143
4144
4145class DiToDate(Func):
4146    pass
4147
4148
4149class Encode(Func):
4150    arg_types = {"this": True, "charset": True}
4151
4152
4153class Exp(Func):
4154    pass
4155
4156
4157class Explode(Func):
4158    pass
4159
4160
4161class Floor(Func):
4162    arg_types = {"this": True, "decimals": False}
4163
4164
4165class FromBase64(Func):
4166    pass
4167
4168
4169class ToBase64(Func):
4170    pass
4171
4172
4173class Greatest(Func):
4174    arg_types = {"this": True, "expressions": False}
4175    is_var_len_args = True
4176
4177
4178class GroupConcat(Func):
4179    arg_types = {"this": True, "separator": False}
4180
4181
4182class Hex(Func):
4183    pass
4184
4185
4186class If(Func):
4187    arg_types = {"this": True, "true": True, "false": False}
4188
4189
4190class Initcap(Func):
4191    arg_types = {"this": True, "expression": False}
4192
4193
4194class JSONKeyValue(Expression):
4195    arg_types = {"this": True, "expression": True}
4196
4197
4198class JSONObject(Func):
4199    arg_types = {
4200        "expressions": False,
4201        "null_handling": False,
4202        "unique_keys": False,
4203        "return_type": False,
4204        "format_json": False,
4205        "encoding": False,
4206    }
4207
4208
4209class OpenJSONColumnDef(Expression):
4210    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
4211
4212
4213class OpenJSON(Func):
4214    arg_types = {"this": True, "path": False, "expressions": False}
4215
4216
4217class JSONBContains(Binary):
4218    _sql_names = ["JSONB_CONTAINS"]
4219
4220
4221class JSONExtract(Binary, Func):
4222    _sql_names = ["JSON_EXTRACT"]
4223
4224
4225class JSONExtractScalar(JSONExtract):
4226    _sql_names = ["JSON_EXTRACT_SCALAR"]
4227
4228
4229class JSONBExtract(JSONExtract):
4230    _sql_names = ["JSONB_EXTRACT"]
4231
4232
4233class JSONBExtractScalar(JSONExtract):
4234    _sql_names = ["JSONB_EXTRACT_SCALAR"]
4235
4236
4237class JSONFormat(Func):
4238    arg_types = {"this": False, "options": False}
4239    _sql_names = ["JSON_FORMAT"]
4240
4241
4242class Least(Func):
4243    arg_types = {"expressions": False}
4244    is_var_len_args = True
4245
4246
4247class Left(Func):
4248    arg_types = {"this": True, "expression": True}
4249
4250
4251class Right(Func):
4252    arg_types = {"this": True, "expression": True}
4253
4254
4255class Length(Func):
4256    _sql_names = ["LENGTH", "LEN"]
4257
4258
4259class Levenshtein(Func):
4260    arg_types = {
4261        "this": True,
4262        "expression": False,
4263        "ins_cost": False,
4264        "del_cost": False,
4265        "sub_cost": False,
4266    }
4267
4268
4269class Ln(Func):
4270    pass
4271
4272
4273class Log(Func):
4274    arg_types = {"this": True, "expression": False}
4275
4276
4277class Log2(Func):
4278    pass
4279
4280
4281class Log10(Func):
4282    pass
4283
4284
4285class LogicalOr(AggFunc):
4286    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
4287
4288
4289class LogicalAnd(AggFunc):
4290    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
4291
4292
4293class Lower(Func):
4294    _sql_names = ["LOWER", "LCASE"]
4295
4296
4297class Map(Func):
4298    arg_types = {"keys": False, "values": False}
4299
4300
4301class MapFromEntries(Func):
4302    pass
4303
4304
4305class StarMap(Func):
4306    pass
4307
4308
4309class VarMap(Func):
4310    arg_types = {"keys": True, "values": True}
4311    is_var_len_args = True
4312
4313    @property
4314    def keys(self) -> t.List[Expression]:
4315        return self.args["keys"].expressions
4316
4317    @property
4318    def values(self) -> t.List[Expression]:
4319        return self.args["values"].expressions
4320
4321
4322# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
4323class MatchAgainst(Func):
4324    arg_types = {"this": True, "expressions": True, "modifier": False}
4325
4326
4327class Max(AggFunc):
4328    arg_types = {"this": True, "expressions": False}
4329    is_var_len_args = True
4330
4331
4332class MD5(Func):
4333    _sql_names = ["MD5"]
4334
4335
4336class Min(AggFunc):
4337    arg_types = {"this": True, "expressions": False}
4338    is_var_len_args = True
4339
4340
4341class Month(Func):
4342    pass
4343
4344
4345class Nvl2(Func):
4346    arg_types = {"this": True, "true": True, "false": False}
4347
4348
4349class Posexplode(Func):
4350    pass
4351
4352
4353class Pow(Binary, Func):
4354    _sql_names = ["POWER", "POW"]
4355
4356
4357class PercentileCont(AggFunc):
4358    arg_types = {"this": True, "expression": False}
4359
4360
4361class PercentileDisc(AggFunc):
4362    arg_types = {"this": True, "expression": False}
4363
4364
4365class Quantile(AggFunc):
4366    arg_types = {"this": True, "quantile": True}
4367
4368
4369class ApproxQuantile(Quantile):
4370    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
4371
4372
4373class RangeN(Func):
4374    arg_types = {"this": True, "expressions": True, "each": False}
4375
4376
4377class ReadCSV(Func):
4378    _sql_names = ["READ_CSV"]
4379    is_var_len_args = True
4380    arg_types = {"this": True, "expressions": False}
4381
4382
4383class Reduce(Func):
4384    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
4385
4386
4387class RegexpExtract(Func):
4388    arg_types = {
4389        "this": True,
4390        "expression": True,
4391        "position": False,
4392        "occurrence": False,
4393        "group": False,
4394    }
4395
4396
4397class RegexpLike(Func):
4398    arg_types = {"this": True, "expression": True, "flag": False}
4399
4400
4401class RegexpILike(Func):
4402    arg_types = {"this": True, "expression": True, "flag": False}
4403
4404
4405# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html
4406# limit is the number of times a pattern is applied
4407class RegexpSplit(Func):
4408    arg_types = {"this": True, "expression": True, "limit": False}
4409
4410
4411class Repeat(Func):
4412    arg_types = {"this": True, "times": True}
4413
4414
4415class Round(Func):
4416    arg_types = {"this": True, "decimals": False}
4417
4418
4419class RowNumber(Func):
4420    arg_types: t.Dict[str, t.Any] = {}
4421
4422
4423class SafeDivide(Func):
4424    arg_types = {"this": True, "expression": True}
4425
4426
4427class SetAgg(AggFunc):
4428    pass
4429
4430
4431class SHA(Func):
4432    _sql_names = ["SHA", "SHA1"]
4433
4434
4435class SHA2(Func):
4436    _sql_names = ["SHA2"]
4437    arg_types = {"this": True, "length": False}
4438
4439
4440class SortArray(Func):
4441    arg_types = {"this": True, "asc": False}
4442
4443
4444class Split(Func):
4445    arg_types = {"this": True, "expression": True, "limit": False}
4446
4447
4448# Start may be omitted in the case of postgres
4449# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
4450class Substring(Func):
4451    arg_types = {"this": True, "start": False, "length": False}
4452
4453
4454class StandardHash(Func):
4455    arg_types = {"this": True, "expression": False}
4456
4457
4458class StrPosition(Func):
4459    arg_types = {
4460        "this": True,
4461        "substr": True,
4462        "position": False,
4463        "instance": False,
4464    }
4465
4466
4467class StrToDate(Func):
4468    arg_types = {"this": True, "format": True}
4469
4470
4471class StrToTime(Func):
4472    arg_types = {"this": True, "format": True}
4473
4474
4475# Spark allows unix_timestamp()
4476# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
4477class StrToUnix(Func):
4478    arg_types = {"this": False, "format": False}
4479
4480
4481class NumberToStr(Func):
4482    arg_types = {"this": True, "format": True}
4483
4484
4485class FromBase(Func):
4486    arg_types = {"this": True, "expression": True}
4487
4488
4489class Struct(Func):
4490    arg_types = {"expressions": True}
4491    is_var_len_args = True
4492
4493
4494class StructExtract(Func):
4495    arg_types = {"this": True, "expression": True}
4496
4497
4498class Sum(AggFunc):
4499    pass
4500
4501
4502class Sqrt(Func):
4503    pass
4504
4505
4506class Stddev(AggFunc):
4507    pass
4508
4509
4510class StddevPop(AggFunc):
4511    pass
4512
4513
4514class StddevSamp(AggFunc):
4515    pass
4516
4517
4518class TimeToStr(Func):
4519    arg_types = {"this": True, "format": True}
4520
4521
4522class TimeToTimeStr(Func):
4523    pass
4524
4525
4526class TimeToUnix(Func):
4527    pass
4528
4529
4530class TimeStrToDate(Func):
4531    pass
4532
4533
4534class TimeStrToTime(Func):
4535    pass
4536
4537
4538class TimeStrToUnix(Func):
4539    pass
4540
4541
4542class Trim(Func):
4543    arg_types = {
4544        "this": True,
4545        "expression": False,
4546        "position": False,
4547        "collation": False,
4548    }
4549
4550
4551class TsOrDsAdd(Func, TimeUnit):
4552    arg_types = {"this": True, "expression": True, "unit": False}
4553
4554
4555class TsOrDsToDateStr(Func):
4556    pass
4557
4558
4559class TsOrDsToDate(Func):
4560    arg_types = {"this": True, "format": False}
4561
4562
4563class TsOrDiToDi(Func):
4564    pass
4565
4566
4567class Unhex(Func):
4568    pass
4569
4570
4571class UnixToStr(Func):
4572    arg_types = {"this": True, "format": False}
4573
4574
4575# https://prestodb.io/docs/current/functions/datetime.html
4576# presto has weird zone/hours/minutes
4577class UnixToTime(Func):
4578    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4579
4580    SECONDS = Literal.string("seconds")
4581    MILLIS = Literal.string("millis")
4582    MICROS = Literal.string("micros")
4583
4584
4585class UnixToTimeStr(Func):
4586    pass
4587
4588
4589class Upper(Func):
4590    _sql_names = ["UPPER", "UCASE"]
4591
4592
4593class Variance(AggFunc):
4594    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
4595
4596
4597class VariancePop(AggFunc):
4598    _sql_names = ["VARIANCE_POP", "VAR_POP"]
4599
4600
4601class Week(Func):
4602    arg_types = {"this": True, "mode": False}
4603
4604
4605class XMLTable(Func):
4606    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
4607
4608
4609class Year(Func):
4610    pass
4611
4612
4613class Use(Expression):
4614    arg_types = {"this": True, "kind": False}
4615
4616
4617class Merge(Expression):
4618    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
4619
4620
4621class When(Func):
4622    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
4623
4624
4625# https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljnextvaluefor.html
4626# https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver16
4627class NextValueFor(Func):
4628    arg_types = {"this": True, "order": False}
4629
4630
4631def _norm_arg(arg):
4632    return arg.lower() if type(arg) is str else arg
4633
4634
4635ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
4636
4637
4638# Helpers
4639@t.overload
4640def maybe_parse(
4641    sql_or_expression: ExpOrStr,
4642    *,
4643    into: t.Type[E],
4644    dialect: DialectType = None,
4645    prefix: t.Optional[str] = None,
4646    copy: bool = False,
4647    **opts,
4648) -> E:
4649    ...
4650
4651
4652@t.overload
4653def maybe_parse(
4654    sql_or_expression: str | E,
4655    *,
4656    into: t.Optional[IntoType] = None,
4657    dialect: DialectType = None,
4658    prefix: t.Optional[str] = None,
4659    copy: bool = False,
4660    **opts,
4661) -> E:
4662    ...
4663
4664
4665def maybe_parse(
4666    sql_or_expression: ExpOrStr,
4667    *,
4668    into: t.Optional[IntoType] = None,
4669    dialect: DialectType = None,
4670    prefix: t.Optional[str] = None,
4671    copy: bool = False,
4672    **opts,
4673) -> Expression:
4674    """Gracefully handle a possible string or expression.
4675
4676    Example:
4677        >>> maybe_parse("1")
4678        (LITERAL this: 1, is_string: False)
4679        >>> maybe_parse(to_identifier("x"))
4680        (IDENTIFIER this: x, quoted: False)
4681
4682    Args:
4683        sql_or_expression: the SQL code string or an expression
4684        into: the SQLGlot Expression to parse into
4685        dialect: the dialect used to parse the input expressions (in the case that an
4686            input expression is a SQL string).
4687        prefix: a string to prefix the sql with before it gets parsed
4688            (automatically includes a space)
4689        copy: whether or not to copy the expression.
4690        **opts: other options to use to parse the input expressions (again, in the case
4691            that an input expression is a SQL string).
4692
4693    Returns:
4694        Expression: the parsed or given expression.
4695    """
4696    if isinstance(sql_or_expression, Expression):
4697        if copy:
4698            return sql_or_expression.copy()
4699        return sql_or_expression
4700
4701    if sql_or_expression is None:
4702        raise ParseError(f"SQL cannot be None")
4703
4704    import sqlglot
4705
4706    sql = str(sql_or_expression)
4707    if prefix:
4708        sql = f"{prefix} {sql}"
4709
4710    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
4711
4712
4713def _maybe_copy(instance: E, copy: bool = True) -> E:
4714    return instance.copy() if copy else instance
4715
4716
4717def _is_wrong_expression(expression, into):
4718    return isinstance(expression, Expression) and not isinstance(expression, into)
4719
4720
4721def _apply_builder(
4722    expression,
4723    instance,
4724    arg,
4725    copy=True,
4726    prefix=None,
4727    into=None,
4728    dialect=None,
4729    **opts,
4730):
4731    if _is_wrong_expression(expression, into):
4732        expression = into(this=expression)
4733    instance = _maybe_copy(instance, copy)
4734    expression = maybe_parse(
4735        sql_or_expression=expression,
4736        prefix=prefix,
4737        into=into,
4738        dialect=dialect,
4739        **opts,
4740    )
4741    instance.set(arg, expression)
4742    return instance
4743
4744
4745def _apply_child_list_builder(
4746    *expressions,
4747    instance,
4748    arg,
4749    append=True,
4750    copy=True,
4751    prefix=None,
4752    into=None,
4753    dialect=None,
4754    properties=None,
4755    **opts,
4756):
4757    instance = _maybe_copy(instance, copy)
4758    parsed = []
4759    for expression in expressions:
4760        if expression is not None:
4761            if _is_wrong_expression(expression, into):
4762                expression = into(expressions=[expression])
4763
4764            expression = maybe_parse(
4765                expression,
4766                into=into,
4767                dialect=dialect,
4768                prefix=prefix,
4769                **opts,
4770            )
4771            parsed.extend(expression.expressions)
4772
4773    existing = instance.args.get(arg)
4774    if append and existing:
4775        parsed = existing.expressions + parsed
4776
4777    child = into(expressions=parsed)
4778    for k, v in (properties or {}).items():
4779        child.set(k, v)
4780    instance.set(arg, child)
4781
4782    return instance
4783
4784
4785def _apply_list_builder(
4786    *expressions,
4787    instance,
4788    arg,
4789    append=True,
4790    copy=True,
4791    prefix=None,
4792    into=None,
4793    dialect=None,
4794    **opts,
4795):
4796    inst = _maybe_copy(instance, copy)
4797
4798    expressions = [
4799        maybe_parse(
4800            sql_or_expression=expression,
4801            into=into,
4802            prefix=prefix,
4803            dialect=dialect,
4804            **opts,
4805        )
4806        for expression in expressions
4807        if expression is not None
4808    ]
4809
4810    existing_expressions = inst.args.get(arg)
4811    if append and existing_expressions:
4812        expressions = existing_expressions + expressions
4813
4814    inst.set(arg, expressions)
4815    return inst
4816
4817
4818def _apply_conjunction_builder(
4819    *expressions,
4820    instance,
4821    arg,
4822    into=None,
4823    append=True,
4824    copy=True,
4825    dialect=None,
4826    **opts,
4827):
4828    expressions = [exp for exp in expressions if exp is not None and exp != ""]
4829    if not expressions:
4830        return instance
4831
4832    inst = _maybe_copy(instance, copy)
4833
4834    existing = inst.args.get(arg)
4835    if append and existing is not None:
4836        expressions = [existing.this if into else existing] + list(expressions)
4837
4838    node = and_(*expressions, dialect=dialect, copy=copy, **opts)
4839
4840    inst.set(arg, into(this=node) if into else node)
4841    return inst
4842
4843
4844def _apply_cte_builder(
4845    instance: E,
4846    alias: ExpOrStr,
4847    as_: ExpOrStr,
4848    recursive: t.Optional[bool] = None,
4849    append: bool = True,
4850    dialect: DialectType = None,
4851    copy: bool = True,
4852    **opts,
4853) -> E:
4854    alias_expression = maybe_parse(alias, dialect=dialect, into=TableAlias, **opts)
4855    as_expression = maybe_parse(as_, dialect=dialect, **opts)
4856    cte = CTE(this=as_expression, alias=alias_expression)
4857    return _apply_child_list_builder(
4858        cte,
4859        instance=instance,
4860        arg="with",
4861        append=append,
4862        copy=copy,
4863        into=With,
4864        properties={"recursive": recursive or False},
4865    )
4866
4867
4868def _combine(
4869    expressions: t.Sequence[t.Optional[ExpOrStr]],
4870    operator: t.Type[Connector],
4871    dialect: DialectType = None,
4872    copy: bool = True,
4873    **opts,
4874) -> Expression:
4875    conditions = [
4876        condition(expression, dialect=dialect, copy=copy, **opts)
4877        for expression in expressions
4878        if expression is not None
4879    ]
4880
4881    this, *rest = conditions
4882    if rest:
4883        this = _wrap(this, Connector)
4884    for expression in rest:
4885        this = operator(this=this, expression=_wrap(expression, Connector))
4886
4887    return this
4888
4889
4890def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren:
4891    return Paren(this=expression) if isinstance(expression, kind) else expression
4892
4893
4894def union(
4895    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4896) -> Union:
4897    """
4898    Initializes a syntax tree from one UNION expression.
4899
4900    Example:
4901        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4902        'SELECT * FROM foo UNION SELECT * FROM bla'
4903
4904    Args:
4905        left: the SQL code string corresponding to the left-hand side.
4906            If an `Expression` instance is passed, it will be used as-is.
4907        right: the SQL code string corresponding to the right-hand side.
4908            If an `Expression` instance is passed, it will be used as-is.
4909        distinct: set the DISTINCT flag if and only if this is true.
4910        dialect: the dialect used to parse the input expression.
4911        opts: other options to use to parse the input expressions.
4912
4913    Returns:
4914        The new Union instance.
4915    """
4916    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4917    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4918
4919    return Union(this=left, expression=right, distinct=distinct)
4920
4921
4922def intersect(
4923    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4924) -> Intersect:
4925    """
4926    Initializes a syntax tree from one INTERSECT expression.
4927
4928    Example:
4929        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4930        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4931
4932    Args:
4933        left: the SQL code string corresponding to the left-hand side.
4934            If an `Expression` instance is passed, it will be used as-is.
4935        right: the SQL code string corresponding to the right-hand side.
4936            If an `Expression` instance is passed, it will be used as-is.
4937        distinct: set the DISTINCT flag if and only if this is true.
4938        dialect: the dialect used to parse the input expression.
4939        opts: other options to use to parse the input expressions.
4940
4941    Returns:
4942        The new Intersect instance.
4943    """
4944    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4945    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4946
4947    return Intersect(this=left, expression=right, distinct=distinct)
4948
4949
4950def except_(
4951    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4952) -> Except:
4953    """
4954    Initializes a syntax tree from one EXCEPT expression.
4955
4956    Example:
4957        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4958        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4959
4960    Args:
4961        left: the SQL code string corresponding to the left-hand side.
4962            If an `Expression` instance is passed, it will be used as-is.
4963        right: the SQL code string corresponding to the right-hand side.
4964            If an `Expression` instance is passed, it will be used as-is.
4965        distinct: set the DISTINCT flag if and only if this is true.
4966        dialect: the dialect used to parse the input expression.
4967        opts: other options to use to parse the input expressions.
4968
4969    Returns:
4970        The new Except instance.
4971    """
4972    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4973    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4974
4975    return Except(this=left, expression=right, distinct=distinct)
4976
4977
4978def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4979    """
4980    Initializes a syntax tree from one or multiple SELECT expressions.
4981
4982    Example:
4983        >>> select("col1", "col2").from_("tbl").sql()
4984        'SELECT col1, col2 FROM tbl'
4985
4986    Args:
4987        *expressions: the SQL code string to parse as the expressions of a
4988            SELECT statement. If an Expression instance is passed, this is used as-is.
4989        dialect: the dialect used to parse the input expressions (in the case that an
4990            input expression is a SQL string).
4991        **opts: other options to use to parse the input expressions (again, in the case
4992            that an input expression is a SQL string).
4993
4994    Returns:
4995        Select: the syntax tree for the SELECT statement.
4996    """
4997    return Select().select(*expressions, dialect=dialect, **opts)
4998
4999
5000def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5001    """
5002    Initializes a syntax tree from a FROM expression.
5003
5004    Example:
5005        >>> from_("tbl").select("col1", "col2").sql()
5006        'SELECT col1, col2 FROM tbl'
5007
5008    Args:
5009        *expression: the SQL code string to parse as the FROM expressions of a
5010            SELECT statement. If an Expression instance is passed, this is used as-is.
5011        dialect: the dialect used to parse the input expression (in the case that the
5012            input expression is a SQL string).
5013        **opts: other options to use to parse the input expressions (again, in the case
5014            that the input expression is a SQL string).
5015
5016    Returns:
5017        Select: the syntax tree for the SELECT statement.
5018    """
5019    return Select().from_(expression, dialect=dialect, **opts)
5020
5021
5022def update(
5023    table: str | Table,
5024    properties: dict,
5025    where: t.Optional[ExpOrStr] = None,
5026    from_: t.Optional[ExpOrStr] = None,
5027    dialect: DialectType = None,
5028    **opts,
5029) -> Update:
5030    """
5031    Creates an update statement.
5032
5033    Example:
5034        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5035        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5036
5037    Args:
5038        *properties: dictionary of properties to set which are
5039            auto converted to sql objects eg None -> NULL
5040        where: sql conditional parsed into a WHERE statement
5041        from_: sql statement parsed into a FROM statement
5042        dialect: the dialect used to parse the input expressions.
5043        **opts: other options to use to parse the input expressions.
5044
5045    Returns:
5046        Update: the syntax tree for the UPDATE statement.
5047    """
5048    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5049    update_expr.set(
5050        "expressions",
5051        [
5052            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5053            for k, v in properties.items()
5054        ],
5055    )
5056    if from_:
5057        update_expr.set(
5058            "from",
5059            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5060        )
5061    if isinstance(where, Condition):
5062        where = Where(this=where)
5063    if where:
5064        update_expr.set(
5065            "where",
5066            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5067        )
5068    return update_expr
5069
5070
5071def delete(
5072    table: ExpOrStr,
5073    where: t.Optional[ExpOrStr] = None,
5074    returning: t.Optional[ExpOrStr] = None,
5075    dialect: DialectType = None,
5076    **opts,
5077) -> Delete:
5078    """
5079    Builds a delete statement.
5080
5081    Example:
5082        >>> delete("my_table", where="id > 1").sql()
5083        'DELETE FROM my_table WHERE id > 1'
5084
5085    Args:
5086        where: sql conditional parsed into a WHERE statement
5087        returning: sql conditional parsed into a RETURNING statement
5088        dialect: the dialect used to parse the input expressions.
5089        **opts: other options to use to parse the input expressions.
5090
5091    Returns:
5092        Delete: the syntax tree for the DELETE statement.
5093    """
5094    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5095    if where:
5096        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5097    if returning:
5098        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5099    return delete_expr
5100
5101
5102def insert(
5103    expression: ExpOrStr,
5104    into: ExpOrStr,
5105    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5106    overwrite: t.Optional[bool] = None,
5107    dialect: DialectType = None,
5108    copy: bool = True,
5109    **opts,
5110) -> Insert:
5111    """
5112    Builds an INSERT statement.
5113
5114    Example:
5115        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5116        'INSERT INTO tbl VALUES (1, 2, 3)'
5117
5118    Args:
5119        expression: the sql string or expression of the INSERT statement
5120        into: the tbl to insert data to.
5121        columns: optionally the table's column names.
5122        overwrite: whether to INSERT OVERWRITE or not.
5123        dialect: the dialect used to parse the input expressions.
5124        copy: whether or not to copy the expression.
5125        **opts: other options to use to parse the input expressions.
5126
5127    Returns:
5128        Insert: the syntax tree for the INSERT statement.
5129    """
5130    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5131    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5132
5133    if columns:
5134        this = _apply_list_builder(
5135            *columns,
5136            instance=Schema(this=this),
5137            arg="expressions",
5138            into=Identifier,
5139            copy=False,
5140            dialect=dialect,
5141            **opts,
5142        )
5143
5144    return Insert(this=this, expression=expr, overwrite=overwrite)
5145
5146
5147def condition(
5148    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5149) -> Condition:
5150    """
5151    Initialize a logical condition expression.
5152
5153    Example:
5154        >>> condition("x=1").sql()
5155        'x = 1'
5156
5157        This is helpful for composing larger logical syntax trees:
5158        >>> where = condition("x=1")
5159        >>> where = where.and_("y=1")
5160        >>> Select().from_("tbl").select("*").where(where).sql()
5161        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5162
5163    Args:
5164        *expression: the SQL code string to parse.
5165            If an Expression instance is passed, this is used as-is.
5166        dialect: the dialect used to parse the input expression (in the case that the
5167            input expression is a SQL string).
5168        copy: Whether or not to copy `expression` (only applies to expressions).
5169        **opts: other options to use to parse the input expressions (again, in the case
5170            that the input expression is a SQL string).
5171
5172    Returns:
5173        The new Condition instance
5174    """
5175    return maybe_parse(
5176        expression,
5177        into=Condition,
5178        dialect=dialect,
5179        copy=copy,
5180        **opts,
5181    )
5182
5183
5184def and_(
5185    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5186) -> Condition:
5187    """
5188    Combine multiple conditions with an AND logical operator.
5189
5190    Example:
5191        >>> and_("x=1", and_("y=1", "z=1")).sql()
5192        'x = 1 AND (y = 1 AND z = 1)'
5193
5194    Args:
5195        *expressions: the SQL code strings to parse.
5196            If an Expression instance is passed, this is used as-is.
5197        dialect: the dialect used to parse the input expression.
5198        copy: whether or not to copy `expressions` (only applies to Expressions).
5199        **opts: other options to use to parse the input expressions.
5200
5201    Returns:
5202        And: the new condition
5203    """
5204    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts))
5205
5206
5207def or_(
5208    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5209) -> Condition:
5210    """
5211    Combine multiple conditions with an OR logical operator.
5212
5213    Example:
5214        >>> or_("x=1", or_("y=1", "z=1")).sql()
5215        'x = 1 OR (y = 1 OR z = 1)'
5216
5217    Args:
5218        *expressions: the SQL code strings to parse.
5219            If an Expression instance is passed, this is used as-is.
5220        dialect: the dialect used to parse the input expression.
5221        copy: whether or not to copy `expressions` (only applies to Expressions).
5222        **opts: other options to use to parse the input expressions.
5223
5224    Returns:
5225        Or: the new condition
5226    """
5227    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts))
5228
5229
5230def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5231    """
5232    Wrap a condition with a NOT operator.
5233
5234    Example:
5235        >>> not_("this_suit='black'").sql()
5236        "NOT this_suit = 'black'"
5237
5238    Args:
5239        expression: the SQL code string to parse.
5240            If an Expression instance is passed, this is used as-is.
5241        dialect: the dialect used to parse the input expression.
5242        copy: whether to copy the expression or not.
5243        **opts: other options to use to parse the input expressions.
5244
5245    Returns:
5246        The new condition.
5247    """
5248    this = condition(
5249        expression,
5250        dialect=dialect,
5251        copy=copy,
5252        **opts,
5253    )
5254    return Not(this=_wrap(this, Connector))
5255
5256
5257def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5258    """
5259    Wrap an expression in parentheses.
5260
5261    Example:
5262        >>> paren("5 + 3").sql()
5263        '(5 + 3)'
5264
5265    Args:
5266        expression: the SQL code string to parse.
5267            If an Expression instance is passed, this is used as-is.
5268        copy: whether to copy the expression or not.
5269
5270    Returns:
5271        The wrapped expression.
5272    """
5273    return Paren(this=maybe_parse(expression, copy=copy))
5274
5275
5276SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
5277
5278
5279@t.overload
5280def to_identifier(name: None, quoted: t.Optional[bool] = None, copy: bool = True) -> None:
5281    ...
5282
5283
5284@t.overload
5285def to_identifier(
5286    name: str | Identifier, quoted: t.Optional[bool] = None, copy: bool = True
5287) -> Identifier:
5288    ...
5289
5290
5291def to_identifier(name, quoted=None, copy=True):
5292    """Builds an identifier.
5293
5294    Args:
5295        name: The name to turn into an identifier.
5296        quoted: Whether or not force quote the identifier.
5297        copy: Whether or not to copy a passed in Identefier node.
5298
5299    Returns:
5300        The identifier ast node.
5301    """
5302
5303    if name is None:
5304        return None
5305
5306    if isinstance(name, Identifier):
5307        identifier = _maybe_copy(name, copy)
5308    elif isinstance(name, str):
5309        identifier = Identifier(
5310            this=name,
5311            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5312        )
5313    else:
5314        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5315    return identifier
5316
5317
5318INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
5319
5320
5321def to_interval(interval: str | Literal) -> Interval:
5322    """Builds an interval expression from a string like '1 day' or '5 months'."""
5323    if isinstance(interval, Literal):
5324        if not interval.is_string:
5325            raise ValueError("Invalid interval string.")
5326
5327        interval = interval.this
5328
5329    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5330
5331    if not interval_parts:
5332        raise ValueError("Invalid interval string.")
5333
5334    return Interval(
5335        this=Literal.string(interval_parts.group(1)),
5336        unit=Var(this=interval_parts.group(2)),
5337    )
5338
5339
5340@t.overload
5341def to_table(sql_path: str | Table, **kwargs) -> Table:
5342    ...
5343
5344
5345@t.overload
5346def to_table(sql_path: None, **kwargs) -> None:
5347    ...
5348
5349
5350def to_table(
5351    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5352) -> t.Optional[Table]:
5353    """
5354    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5355    If a table is passed in then that table is returned.
5356
5357    Args:
5358        sql_path: a `[catalog].[schema].[table]` string.
5359        dialect: the source dialect according to which the table name will be parsed.
5360        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5361
5362    Returns:
5363        A table expression.
5364    """
5365    if sql_path is None or isinstance(sql_path, Table):
5366        return sql_path
5367    if not isinstance(sql_path, str):
5368        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5369
5370    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5371    if table:
5372        for k, v in kwargs.items():
5373            table.set(k, v)
5374
5375    return table
5376
5377
5378def to_column(sql_path: str | Column, **kwargs) -> Column:
5379    """
5380    Create a column from a `[table].[column]` sql path. Schema is optional.
5381
5382    If a column is passed in then that column is returned.
5383
5384    Args:
5385        sql_path: `[table].[column]` string
5386    Returns:
5387        Table: A column expression
5388    """
5389    if sql_path is None or isinstance(sql_path, Column):
5390        return sql_path
5391    if not isinstance(sql_path, str):
5392        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5393    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore
5394
5395
5396def alias_(
5397    expression: ExpOrStr,
5398    alias: str | Identifier,
5399    table: bool | t.Sequence[str | Identifier] = False,
5400    quoted: t.Optional[bool] = None,
5401    dialect: DialectType = None,
5402    copy: bool = True,
5403    **opts,
5404):
5405    """Create an Alias expression.
5406
5407    Example:
5408        >>> alias_('foo', 'bar').sql()
5409        'foo AS bar'
5410
5411        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5412        '(SELECT 1, 2) AS bar(a, b)'
5413
5414    Args:
5415        expression: the SQL code strings to parse.
5416            If an Expression instance is passed, this is used as-is.
5417        alias: the alias name to use. If the name has
5418            special characters it is quoted.
5419        table: Whether or not to create a table alias, can also be a list of columns.
5420        quoted: whether or not to quote the alias
5421        dialect: the dialect used to parse the input expression.
5422        copy: Whether or not to copy the expression.
5423        **opts: other options to use to parse the input expressions.
5424
5425    Returns:
5426        Alias: the aliased expression
5427    """
5428    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5429    alias = to_identifier(alias, quoted=quoted)
5430
5431    if table:
5432        table_alias = TableAlias(this=alias)
5433        exp.set("alias", table_alias)
5434
5435        if not isinstance(table, bool):
5436            for column in table:
5437                table_alias.append("columns", to_identifier(column, quoted=quoted))
5438
5439        return exp
5440
5441    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5442    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5443    # for the complete Window expression.
5444    #
5445    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5446
5447    if "alias" in exp.arg_types and not isinstance(exp, Window):
5448        exp.set("alias", alias)
5449        return exp
5450    return Alias(this=exp, alias=alias)
5451
5452
5453def subquery(
5454    expression: ExpOrStr,
5455    alias: t.Optional[Identifier | str] = None,
5456    dialect: DialectType = None,
5457    **opts,
5458) -> Select:
5459    """
5460    Build a subquery expression.
5461
5462    Example:
5463        >>> subquery('select x from tbl', 'bar').select('x').sql()
5464        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5465
5466    Args:
5467        expression: the SQL code strings to parse.
5468            If an Expression instance is passed, this is used as-is.
5469        alias: the alias name to use.
5470        dialect: the dialect used to parse the input expression.
5471        **opts: other options to use to parse the input expressions.
5472
5473    Returns:
5474        A new Select instance with the subquery expression included.
5475    """
5476
5477    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5478    return Select().from_(expression, dialect=dialect, **opts)
5479
5480
5481def column(
5482    col: str | Identifier,
5483    table: t.Optional[str | Identifier] = None,
5484    db: t.Optional[str | Identifier] = None,
5485    catalog: t.Optional[str | Identifier] = None,
5486    quoted: t.Optional[bool] = None,
5487) -> Column:
5488    """
5489    Build a Column.
5490
5491    Args:
5492        col: Column name.
5493        table: Table name.
5494        db: Database name.
5495        catalog: Catalog name.
5496        quoted: Whether to force quotes on the column's identifiers.
5497
5498    Returns:
5499        The new Column instance.
5500    """
5501    return Column(
5502        this=to_identifier(col, quoted=quoted),
5503        table=to_identifier(table, quoted=quoted),
5504        db=to_identifier(db, quoted=quoted),
5505        catalog=to_identifier(catalog, quoted=quoted),
5506    )
5507
5508
5509def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5510    """Cast an expression to a data type.
5511
5512    Example:
5513        >>> cast('x + 1', 'int').sql()
5514        'CAST(x + 1 AS INT)'
5515
5516    Args:
5517        expression: The expression to cast.
5518        to: The datatype to cast to.
5519
5520    Returns:
5521        The new Cast instance.
5522    """
5523    expression = maybe_parse(expression, **opts)
5524    return Cast(this=expression, to=DataType.build(to, **opts))
5525
5526
5527def table_(
5528    table: Identifier | str,
5529    db: t.Optional[Identifier | str] = None,
5530    catalog: t.Optional[Identifier | str] = None,
5531    quoted: t.Optional[bool] = None,
5532    alias: t.Optional[Identifier | str] = None,
5533) -> Table:
5534    """Build a Table.
5535
5536    Args:
5537        table: Table name.
5538        db: Database name.
5539        catalog: Catalog name.
5540        quote: Whether to force quotes on the table's identifiers.
5541        alias: Table's alias.
5542
5543    Returns:
5544        The new Table instance.
5545    """
5546    return Table(
5547        this=to_identifier(table, quoted=quoted),
5548        db=to_identifier(db, quoted=quoted),
5549        catalog=to_identifier(catalog, quoted=quoted),
5550        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5551    )
5552
5553
5554def values(
5555    values: t.Iterable[t.Tuple[t.Any, ...]],
5556    alias: t.Optional[str] = None,
5557    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5558) -> Values:
5559    """Build VALUES statement.
5560
5561    Example:
5562        >>> values([(1, '2')]).sql()
5563        "VALUES (1, '2')"
5564
5565    Args:
5566        values: values statements that will be converted to SQL
5567        alias: optional alias
5568        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5569         If either are provided then an alias is also required.
5570
5571    Returns:
5572        Values: the Values expression object
5573    """
5574    if columns and not alias:
5575        raise ValueError("Alias is required when providing columns")
5576
5577    return Values(
5578        expressions=[convert(tup) for tup in values],
5579        alias=(
5580            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5581            if columns
5582            else (TableAlias(this=to_identifier(alias)) if alias else None)
5583        ),
5584    )
5585
5586
5587def var(name: t.Optional[ExpOrStr]) -> Var:
5588    """Build a SQL variable.
5589
5590    Example:
5591        >>> repr(var('x'))
5592        '(VAR this: x)'
5593
5594        >>> repr(var(column('x', table='y')))
5595        '(VAR this: x)'
5596
5597    Args:
5598        name: The name of the var or an expression who's name will become the var.
5599
5600    Returns:
5601        The new variable node.
5602    """
5603    if not name:
5604        raise ValueError("Cannot convert empty name into var.")
5605
5606    if isinstance(name, Expression):
5607        name = name.name
5608    return Var(this=name)
5609
5610
5611def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5612    """Build ALTER TABLE... RENAME... expression
5613
5614    Args:
5615        old_name: The old name of the table
5616        new_name: The new name of the table
5617
5618    Returns:
5619        Alter table expression
5620    """
5621    old_table = to_table(old_name)
5622    new_table = to_table(new_name)
5623    return AlterTable(
5624        this=old_table,
5625        actions=[
5626            RenameTable(this=new_table),
5627        ],
5628    )
5629
5630
5631def convert(value: t.Any, copy: bool = False) -> Expression:
5632    """Convert a python value into an expression object.
5633
5634    Raises an error if a conversion is not possible.
5635
5636    Args:
5637        value: A python object.
5638        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5639
5640    Returns:
5641        Expression: the equivalent expression object.
5642    """
5643    if isinstance(value, Expression):
5644        return _maybe_copy(value, copy)
5645    if isinstance(value, str):
5646        return Literal.string(value)
5647    if isinstance(value, bool):
5648        return Boolean(this=value)
5649    if value is None or (isinstance(value, float) and math.isnan(value)):
5650        return NULL
5651    if isinstance(value, numbers.Number):
5652        return Literal.number(value)
5653    if isinstance(value, datetime.datetime):
5654        datetime_literal = Literal.string(
5655            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5656        )
5657        return TimeStrToTime(this=datetime_literal)
5658    if isinstance(value, datetime.date):
5659        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5660        return DateStrToDate(this=date_literal)
5661    if isinstance(value, tuple):
5662        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5663    if isinstance(value, list):
5664        return Array(expressions=[convert(v, copy=copy) for v in value])
5665    if isinstance(value, dict):
5666        return Map(
5667            keys=[convert(k, copy=copy) for k in value],
5668            values=[convert(v, copy=copy) for v in value.values()],
5669        )
5670    raise ValueError(f"Cannot convert {value}")
5671
5672
5673def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5674    """
5675    Replace children of an expression with the result of a lambda fun(child) -> exp.
5676    """
5677    for k, v in expression.args.items():
5678        is_list_arg = type(v) is list
5679
5680        child_nodes = v if is_list_arg else [v]
5681        new_child_nodes = []
5682
5683        for cn in child_nodes:
5684            if isinstance(cn, Expression):
5685                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5686                    new_child_nodes.append(child_node)
5687                    child_node.parent = expression
5688                    child_node.arg_key = k
5689            else:
5690                new_child_nodes.append(cn)
5691
5692        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
5693
5694
5695def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5696    """
5697    Return all table names referenced through columns in an expression.
5698
5699    Example:
5700        >>> import sqlglot
5701        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5702        ['a', 'c']
5703
5704    Args:
5705        expression: expression to find table names.
5706        exclude: a table name to exclude
5707
5708    Returns:
5709        A list of unique names.
5710    """
5711    return {
5712        table
5713        for table in (column.table for column in expression.find_all(Column))
5714        if table and table != exclude
5715    }
5716
5717
5718def table_name(table: Table | str, dialect: DialectType = None) -> str:
5719    """Get the full name of a table as a string.
5720
5721    Args:
5722        table: Table expression node or string.
5723        dialect: The dialect to generate the table name for.
5724
5725    Examples:
5726        >>> from sqlglot import exp, parse_one
5727        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5728        'a.b.c'
5729
5730    Returns:
5731        The table name.
5732    """
5733
5734    table = maybe_parse(table, into=Table)
5735
5736    if not table:
5737        raise ValueError(f"Cannot parse {table}")
5738
5739    return ".".join(
5740        part.sql(dialect=dialect) if not SAFE_IDENTIFIER_RE.match(part.name) else part.name
5741        for part in table.parts
5742    )
5743
5744
5745def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5746    """Replace all tables in expression according to the mapping.
5747
5748    Args:
5749        expression: expression node to be transformed and replaced.
5750        mapping: mapping of table names.
5751        copy: whether or not to copy the expression.
5752
5753    Examples:
5754        >>> from sqlglot import exp, parse_one
5755        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5756        'SELECT * FROM c'
5757
5758    Returns:
5759        The mapped expression.
5760    """
5761
5762    def _replace_tables(node: Expression) -> Expression:
5763        if isinstance(node, Table):
5764            new_name = mapping.get(table_name(node))
5765            if new_name:
5766                return to_table(
5767                    new_name,
5768                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5769                )
5770        return node
5771
5772    return expression.transform(_replace_tables, copy=copy)
5773
5774
5775def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5776    """Replace placeholders in an expression.
5777
5778    Args:
5779        expression: expression node to be transformed and replaced.
5780        args: positional names that will substitute unnamed placeholders in the given order.
5781        kwargs: keyword arguments that will substitute named placeholders.
5782
5783    Examples:
5784        >>> from sqlglot import exp, parse_one
5785        >>> replace_placeholders(
5786        ...     parse_one("select * from :tbl where ? = ?"),
5787        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5788        ... ).sql()
5789        "SELECT * FROM foo WHERE str_col = 'b'"
5790
5791    Returns:
5792        The mapped expression.
5793    """
5794
5795    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5796        if isinstance(node, Placeholder):
5797            if node.name:
5798                new_name = kwargs.get(node.name)
5799                if new_name:
5800                    return convert(new_name)
5801            else:
5802                try:
5803                    return convert(next(args))
5804                except StopIteration:
5805                    pass
5806        return node
5807
5808    return expression.transform(_replace_placeholders, iter(args), **kwargs)
5809
5810
5811def expand(
5812    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5813) -> Expression:
5814    """Transforms an expression by expanding all referenced sources into subqueries.
5815
5816    Examples:
5817        >>> from sqlglot import parse_one
5818        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5819        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5820
5821        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5822        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5823
5824    Args:
5825        expression: The expression to expand.
5826        sources: A dictionary of name to Subqueryables.
5827        copy: Whether or not to copy the expression during transformation. Defaults to True.
5828
5829    Returns:
5830        The transformed expression.
5831    """
5832
5833    def _expand(node: Expression):
5834        if isinstance(node, Table):
5835            name = table_name(node)
5836            source = sources.get(name)
5837            if source:
5838                subquery = source.subquery(node.alias or name)
5839                subquery.comments = [f"source: {name}"]
5840                return subquery.transform(_expand, copy=False)
5841        return node
5842
5843    return expression.transform(_expand, copy=copy)
5844
5845
5846def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5847    """
5848    Returns a Func expression.
5849
5850    Examples:
5851        >>> func("abs", 5).sql()
5852        'ABS(5)'
5853
5854        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5855        'CAST(5 AS DOUBLE)'
5856
5857    Args:
5858        name: the name of the function to build.
5859        args: the args used to instantiate the function of interest.
5860        dialect: the source dialect.
5861        kwargs: the kwargs used to instantiate the function of interest.
5862
5863    Note:
5864        The arguments `args` and `kwargs` are mutually exclusive.
5865
5866    Returns:
5867        An instance of the function of interest, or an anonymous function, if `name` doesn't
5868        correspond to an existing `sqlglot.expressions.Func` class.
5869    """
5870    if args and kwargs:
5871        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5872
5873    from sqlglot.dialects.dialect import Dialect
5874
5875    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5876    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5877
5878    parser = Dialect.get_or_raise(dialect)().parser()
5879    from_args_list = parser.FUNCTIONS.get(name.upper())
5880
5881    if from_args_list:
5882        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5883    else:
5884        kwargs = kwargs or {"expressions": converted}
5885        function = Anonymous(this=name, **kwargs)
5886
5887    for error_message in function.error_messages(converted):
5888        raise ValueError(error_message)
5889
5890    return function
5891
5892
5893def true() -> Boolean:
5894    """
5895    Returns a true Boolean expression.
5896    """
5897    return Boolean(this=True)
5898
5899
5900def false() -> Boolean:
5901    """
5902    Returns a false Boolean expression.
5903    """
5904    return Boolean(this=False)
5905
5906
5907def null() -> Null:
5908    """
5909    Returns a Null expression.
5910    """
5911    return Null()
5912
5913
5914# TODO: deprecate this
5915TRUE = Boolean(this=True)
5916FALSE = Boolean(this=False)
5917NULL = Null()
class Expression:
 55class Expression(metaclass=_Expression):
 56    """
 57    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
 58    context, such as its child expressions, their names (arg keys), and whether a given child expression
 59    is optional or not.
 60
 61    Attributes:
 62        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
 63            and representing expressions as strings.
 64        arg_types: determines what arguments (child nodes) are supported by an expression. It
 65            maps arg keys to booleans that indicate whether the corresponding args are optional.
 66        parent: a reference to the parent expression (or None, in case of root expressions).
 67        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
 68            uses to refer to it.
 69        comments: a list of comments that are associated with a given expression. This is used in
 70            order to preserve comments when transpiling SQL code.
 71        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
 72            optimizer, in order to enable some transformations that require type information.
 73
 74    Example:
 75        >>> class Foo(Expression):
 76        ...     arg_types = {"this": True, "expression": False}
 77
 78        The above definition informs us that Foo is an Expression that requires an argument called
 79        "this" and may also optionally receive an argument called "expression".
 80
 81    Args:
 82        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
 83    """
 84
 85    key = "expression"
 86    arg_types = {"this": True}
 87    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
 88
 89    def __init__(self, **args: t.Any):
 90        self.args: t.Dict[str, t.Any] = args
 91        self.parent: t.Optional[Expression] = None
 92        self.arg_key: t.Optional[str] = None
 93        self.comments: t.Optional[t.List[str]] = None
 94        self._type: t.Optional[DataType] = None
 95        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 96        self._hash: t.Optional[int] = None
 97
 98        for arg_key, value in self.args.items():
 99            self._set_parent(arg_key, value)
100
101    def __eq__(self, other) -> bool:
102        return type(self) is type(other) and hash(self) == hash(other)
103
104    @property
105    def hashable_args(self) -> t.Any:
106        args = (self.args.get(k) for k in self.arg_types)
107
108        return tuple(
109            (tuple(_norm_arg(a) for a in arg) if arg else None)
110            if type(arg) is list
111            else (_norm_arg(arg) if arg is not None and arg is not False else None)
112            for arg in args
113        )
114
115    def __hash__(self) -> int:
116        if self._hash is not None:
117            return self._hash
118
119        return hash((self.__class__, self.hashable_args))
120
121    @property
122    def this(self):
123        """
124        Retrieves the argument with key "this".
125        """
126        return self.args.get("this")
127
128    @property
129    def expression(self):
130        """
131        Retrieves the argument with key "expression".
132        """
133        return self.args.get("expression")
134
135    @property
136    def expressions(self):
137        """
138        Retrieves the argument with key "expressions".
139        """
140        return self.args.get("expressions") or []
141
142    def text(self, key) -> str:
143        """
144        Returns a textual representation of the argument corresponding to "key". This can only be used
145        for args that are strings or leaf Expression instances, such as identifiers and literals.
146        """
147        field = self.args.get(key)
148        if isinstance(field, str):
149            return field
150        if isinstance(field, (Identifier, Literal, Var)):
151            return field.this
152        if isinstance(field, (Star, Null)):
153            return field.name
154        return ""
155
156    @property
157    def is_string(self) -> bool:
158        """
159        Checks whether a Literal expression is a string.
160        """
161        return isinstance(self, Literal) and self.args["is_string"]
162
163    @property
164    def is_number(self) -> bool:
165        """
166        Checks whether a Literal expression is a number.
167        """
168        return isinstance(self, Literal) and not self.args["is_string"]
169
170    @property
171    def is_int(self) -> bool:
172        """
173        Checks whether a Literal expression is an integer.
174        """
175        if self.is_number:
176            try:
177                int(self.name)
178                return True
179            except ValueError:
180                pass
181        return False
182
183    @property
184    def is_star(self) -> bool:
185        """Checks whether an expression is a star."""
186        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
187
188    @property
189    def alias(self) -> str:
190        """
191        Returns the alias of the expression, or an empty string if it's not aliased.
192        """
193        if isinstance(self.args.get("alias"), TableAlias):
194            return self.args["alias"].name
195        return self.text("alias")
196
197    @property
198    def name(self) -> str:
199        return self.text("this")
200
201    @property
202    def alias_or_name(self) -> str:
203        return self.alias or self.name
204
205    @property
206    def output_name(self) -> str:
207        """
208        Name of the output column if this expression is a selection.
209
210        If the Expression has no output name, an empty string is returned.
211
212        Example:
213            >>> from sqlglot import parse_one
214            >>> parse_one("SELECT a").expressions[0].output_name
215            'a'
216            >>> parse_one("SELECT b AS c").expressions[0].output_name
217            'c'
218            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
219            ''
220        """
221        return ""
222
223    @property
224    def type(self) -> t.Optional[DataType]:
225        return self._type
226
227    @type.setter
228    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
229        if dtype and not isinstance(dtype, DataType):
230            dtype = DataType.build(dtype)
231        self._type = dtype  # type: ignore
232
233    @property
234    def meta(self) -> t.Dict[str, t.Any]:
235        if self._meta is None:
236            self._meta = {}
237        return self._meta
238
239    def __deepcopy__(self, memo):
240        copy = self.__class__(**deepcopy(self.args))
241        if self.comments is not None:
242            copy.comments = deepcopy(self.comments)
243
244        if self._type is not None:
245            copy._type = self._type.copy()
246
247        if self._meta is not None:
248            copy._meta = deepcopy(self._meta)
249
250        return copy
251
252    def copy(self):
253        """
254        Returns a deep copy of the expression.
255        """
256        new = deepcopy(self)
257        new.parent = self.parent
258        return new
259
260    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
261        if self.comments is None:
262            self.comments = []
263        if comments:
264            self.comments.extend(comments)
265
266    def append(self, arg_key: str, value: t.Any) -> None:
267        """
268        Appends value to arg_key if it's a list or sets it as a new list.
269
270        Args:
271            arg_key (str): name of the list expression arg
272            value (Any): value to append to the list
273        """
274        if not isinstance(self.args.get(arg_key), list):
275            self.args[arg_key] = []
276        self.args[arg_key].append(value)
277        self._set_parent(arg_key, value)
278
279    def set(self, arg_key: str, value: t.Any) -> None:
280        """
281        Sets `arg_key` to `value`.
282
283        Args:
284            arg_key (str): name of the expression arg.
285            value: value to set the arg to.
286        """
287        self.args[arg_key] = value
288        self._set_parent(arg_key, value)
289
290    def _set_parent(self, arg_key: str, value: t.Any) -> None:
291        if hasattr(value, "parent"):
292            value.parent = self
293            value.arg_key = arg_key
294        elif type(value) is list:
295            for v in value:
296                if hasattr(v, "parent"):
297                    v.parent = self
298                    v.arg_key = arg_key
299
300    @property
301    def depth(self) -> int:
302        """
303        Returns the depth of this tree.
304        """
305        if self.parent:
306            return self.parent.depth + 1
307        return 0
308
309    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
310        """Yields the key and expression for all arguments, exploding list args."""
311        for k, vs in self.args.items():
312            if type(vs) is list:
313                for v in vs:
314                    if hasattr(v, "parent"):
315                        yield k, v
316            else:
317                if hasattr(vs, "parent"):
318                    yield k, vs
319
320    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
321        """
322        Returns the first node in this tree which matches at least one of
323        the specified types.
324
325        Args:
326            expression_types: the expression type(s) to match.
327            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
328
329        Returns:
330            The node which matches the criteria or None if no such node was found.
331        """
332        return next(self.find_all(*expression_types, bfs=bfs), None)
333
334    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
335        """
336        Returns a generator object which visits all nodes in this tree and only
337        yields those that match at least one of the specified expression types.
338
339        Args:
340            expression_types: the expression type(s) to match.
341            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
342
343        Returns:
344            The generator object.
345        """
346        for expression, *_ in self.walk(bfs=bfs):
347            if isinstance(expression, expression_types):
348                yield expression
349
350    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
351        """
352        Returns a nearest parent matching expression_types.
353
354        Args:
355            expression_types: the expression type(s) to match.
356
357        Returns:
358            The parent node.
359        """
360        ancestor = self.parent
361        while ancestor and not isinstance(ancestor, expression_types):
362            ancestor = ancestor.parent
363        return t.cast(E, ancestor)
364
365    @property
366    def parent_select(self) -> t.Optional[Select]:
367        """
368        Returns the parent select statement.
369        """
370        return self.find_ancestor(Select)
371
372    @property
373    def same_parent(self) -> bool:
374        """Returns if the parent is the same class as itself."""
375        return type(self.parent) is self.__class__
376
377    def root(self) -> Expression:
378        """
379        Returns the root expression of this tree.
380        """
381        expression = self
382        while expression.parent:
383            expression = expression.parent
384        return expression
385
386    def walk(self, bfs=True, prune=None):
387        """
388        Returns a generator object which visits all nodes in this tree.
389
390        Args:
391            bfs (bool): if set to True the BFS traversal order will be applied,
392                otherwise the DFS traversal will be used instead.
393            prune ((node, parent, arg_key) -> bool): callable that returns True if
394                the generator should stop traversing this branch of the tree.
395
396        Returns:
397            the generator object.
398        """
399        if bfs:
400            yield from self.bfs(prune=prune)
401        else:
402            yield from self.dfs(prune=prune)
403
404    def dfs(self, parent=None, key=None, prune=None):
405        """
406        Returns a generator object which visits all nodes in this tree in
407        the DFS (Depth-first) order.
408
409        Returns:
410            The generator object.
411        """
412        parent = parent or self.parent
413        yield self, parent, key
414        if prune and prune(self, parent, key):
415            return
416
417        for k, v in self.iter_expressions():
418            yield from v.dfs(self, k, prune)
419
420    def bfs(self, prune=None):
421        """
422        Returns a generator object which visits all nodes in this tree in
423        the BFS (Breadth-first) order.
424
425        Returns:
426            The generator object.
427        """
428        queue = deque([(self, self.parent, None)])
429
430        while queue:
431            item, parent, key = queue.popleft()
432
433            yield item, parent, key
434            if prune and prune(item, parent, key):
435                continue
436
437            for k, v in item.iter_expressions():
438                queue.append((v, item, k))
439
440    def unnest(self):
441        """
442        Returns the first non parenthesis child or self.
443        """
444        expression = self
445        while type(expression) is Paren:
446            expression = expression.this
447        return expression
448
449    def unalias(self):
450        """
451        Returns the inner expression if this is an Alias.
452        """
453        if isinstance(self, Alias):
454            return self.this
455        return self
456
457    def unnest_operands(self):
458        """
459        Returns unnested operands as a tuple.
460        """
461        return tuple(arg.unnest() for _, arg in self.iter_expressions())
462
463    def flatten(self, unnest=True):
464        """
465        Returns a generator which yields child nodes who's parents are the same class.
466
467        A AND B AND C -> [A, B, C]
468        """
469        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
470            if not type(node) is self.__class__:
471                yield node.unnest() if unnest else node
472
473    def __str__(self) -> str:
474        return self.sql()
475
476    def __repr__(self) -> str:
477        return self._to_s()
478
479    def sql(self, dialect: DialectType = None, **opts) -> str:
480        """
481        Returns SQL string representation of this tree.
482
483        Args:
484            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
485            opts: other `sqlglot.generator.Generator` options.
486
487        Returns:
488            The SQL string.
489        """
490        from sqlglot.dialects import Dialect
491
492        return Dialect.get_or_raise(dialect)().generate(self, **opts)
493
494    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
495        indent = "" if not level else "\n"
496        indent += "".join(["  "] * level)
497        left = f"({self.key.upper()} "
498
499        args: t.Dict[str, t.Any] = {
500            k: ", ".join(
501                v._to_s(hide_missing=hide_missing, level=level + 1)
502                if hasattr(v, "_to_s")
503                else str(v)
504                for v in ensure_list(vs)
505                if v is not None
506            )
507            for k, vs in self.args.items()
508        }
509        args["comments"] = self.comments
510        args["type"] = self.type
511        args = {k: v for k, v in args.items() if v or not hide_missing}
512
513        right = ", ".join(f"{k}: {v}" for k, v in args.items())
514        right += ")"
515
516        return indent + left + right
517
518    def transform(self, fun, *args, copy=True, **kwargs):
519        """
520        Recursively visits all tree nodes (excluding already transformed ones)
521        and applies the given transformation function to each node.
522
523        Args:
524            fun (function): a function which takes a node as an argument and returns a
525                new transformed node or the same node without modifications. If the function
526                returns None, then the corresponding node will be removed from the syntax tree.
527            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
528                modified in place.
529
530        Returns:
531            The transformed tree.
532        """
533        node = self.copy() if copy else self
534        new_node = fun(node, *args, **kwargs)
535
536        if new_node is None or not isinstance(new_node, Expression):
537            return new_node
538        if new_node is not node:
539            new_node.parent = node.parent
540            return new_node
541
542        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
543        return new_node
544
545    @t.overload
546    def replace(self, expression: E) -> E:
547        ...
548
549    @t.overload
550    def replace(self, expression: None) -> None:
551        ...
552
553    def replace(self, expression):
554        """
555        Swap out this expression with a new expression.
556
557        For example::
558
559            >>> tree = Select().select("x").from_("tbl")
560            >>> tree.find(Column).replace(Column(this="y"))
561            (COLUMN this: y)
562            >>> tree.sql()
563            'SELECT y FROM tbl'
564
565        Args:
566            expression: new node
567
568        Returns:
569            The new expression or expressions.
570        """
571        if not self.parent:
572            return expression
573
574        parent = self.parent
575        self.parent = None
576
577        replace_children(parent, lambda child: expression if child is self else child)
578        return expression
579
580    def pop(self: E) -> E:
581        """
582        Remove this expression from its AST.
583
584        Returns:
585            The popped expression.
586        """
587        self.replace(None)
588        return self
589
590    def assert_is(self, type_: t.Type[E]) -> E:
591        """
592        Assert that this `Expression` is an instance of `type_`.
593
594        If it is NOT an instance of `type_`, this raises an assertion error.
595        Otherwise, this returns this expression.
596
597        Examples:
598            This is useful for type security in chained expressions:
599
600            >>> import sqlglot
601            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
602            'SELECT x, z FROM y'
603        """
604        assert isinstance(self, type_)
605        return self
606
607    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
608        """
609        Checks if this expression is valid (e.g. all mandatory args are set).
610
611        Args:
612            args: a sequence of values that were used to instantiate a Func expression. This is used
613                to check that the provided arguments don't exceed the function argument limit.
614
615        Returns:
616            A list of error messages for all possible errors that were found.
617        """
618        errors: t.List[str] = []
619
620        for k in self.args:
621            if k not in self.arg_types:
622                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
623        for k, mandatory in self.arg_types.items():
624            v = self.args.get(k)
625            if mandatory and (v is None or (isinstance(v, list) and not v)):
626                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
627
628        if (
629            args
630            and isinstance(self, Func)
631            and len(args) > len(self.arg_types)
632            and not self.is_var_len_args
633        ):
634            errors.append(
635                f"The number of provided arguments ({len(args)}) is greater than "
636                f"the maximum number of supported arguments ({len(self.arg_types)})"
637            )
638
639        return errors
640
641    def dump(self):
642        """
643        Dump this Expression to a JSON-serializable dict.
644        """
645        from sqlglot.serde import dump
646
647        return dump(self)
648
649    @classmethod
650    def load(cls, obj):
651        """
652        Load a dict (as returned by `Expression.dump`) into an Expression instance.
653        """
654        from sqlglot.serde import load
655
656        return load(obj)

The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.

Attributes:
  • key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • _type: the sqlglot.expressions.DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Example:
>>> class Foo(Expression):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
Expression(**args: Any)
89    def __init__(self, **args: t.Any):
90        self.args: t.Dict[str, t.Any] = args
91        self.parent: t.Optional[Expression] = None
92        self.arg_key: t.Optional[str] = None
93        self.comments: t.Optional[t.List[str]] = None
94        self._type: t.Optional[DataType] = None
95        self._meta: t.Optional[t.Dict[str, t.Any]] = None
96        self._hash: t.Optional[int] = None
97
98        for arg_key, value in self.args.items():
99            self._set_parent(arg_key, value)
key = 'expression'
arg_types = {'this': True}
args: Dict[str, Any]
parent: Optional[sqlglot.expressions.Expression]
arg_key: Optional[str]
comments: Optional[List[str]]
hashable_args: Any
this

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
142    def text(self, key) -> str:
143        """
144        Returns a textual representation of the argument corresponding to "key". This can only be used
145        for args that are strings or leaf Expression instances, such as identifiers and literals.
146        """
147        field = self.args.get(key)
148        if isinstance(field, str):
149            return field
150        if isinstance(field, (Identifier, Literal, Var)):
151            return field.this
152        if isinstance(field, (Star, Null)):
153            return field.name
154        return ""

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

Returns the alias of the expression, or an empty string if it's not aliased.

name: str
alias_or_name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
meta: Dict[str, Any]
def copy(self):
252    def copy(self):
253        """
254        Returns a deep copy of the expression.
255        """
256        new = deepcopy(self)
257        new.parent = self.parent
258        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
260    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
261        if self.comments is None:
262            self.comments = []
263        if comments:
264            self.comments.extend(comments)
def append(self, arg_key: str, value: Any) -> None:
266    def append(self, arg_key: str, value: t.Any) -> None:
267        """
268        Appends value to arg_key if it's a list or sets it as a new list.
269
270        Args:
271            arg_key (str): name of the list expression arg
272            value (Any): value to append to the list
273        """
274        if not isinstance(self.args.get(arg_key), list):
275            self.args[arg_key] = []
276        self.args[arg_key].append(value)
277        self._set_parent(arg_key, value)

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key: str, value: Any) -> None:
279    def set(self, arg_key: str, value: t.Any) -> None:
280        """
281        Sets `arg_key` to `value`.
282
283        Args:
284            arg_key (str): name of the expression arg.
285            value: value to set the arg to.
286        """
287        self.args[arg_key] = value
288        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key (str): name of the expression arg.
  • value: value to set the arg to.
depth: int

Returns the depth of this tree.

def iter_expressions(self) -> Iterator[Tuple[str, sqlglot.expressions.Expression]]:
309    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
310        """Yields the key and expression for all arguments, exploding list args."""
311        for k, vs in self.args.items():
312            if type(vs) is list:
313                for v in vs:
314                    if hasattr(v, "parent"):
315                        yield k, v
316            else:
317                if hasattr(vs, "parent"):
318                    yield k, vs

Yields the key and expression for all arguments, exploding list args.

def find(self, *expression_types: Type[~E], bfs: bool = True) -> Optional[~E]:
320    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
321        """
322        Returns the first node in this tree which matches at least one of
323        the specified types.
324
325        Args:
326            expression_types: the expression type(s) to match.
327            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
328
329        Returns:
330            The node which matches the criteria or None if no such node was found.
331        """
332        return next(self.find_all(*expression_types, bfs=bfs), None)

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: Type[~E], bfs: bool = True) -> Iterator[~E]:
334    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
335        """
336        Returns a generator object which visits all nodes in this tree and only
337        yields those that match at least one of the specified expression types.
338
339        Args:
340            expression_types: the expression type(s) to match.
341            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
342
343        Returns:
344            The generator object.
345        """
346        for expression, *_ in self.walk(bfs=bfs):
347            if isinstance(expression, expression_types):
348                yield expression

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
350    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
351        """
352        Returns a nearest parent matching expression_types.
353
354        Args:
355            expression_types: the expression type(s) to match.
356
357        Returns:
358            The parent node.
359        """
360        ancestor = self.parent
361        while ancestor and not isinstance(ancestor, expression_types):
362            ancestor = ancestor.parent
363        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select: Optional[sqlglot.expressions.Select]

Returns the parent select statement.

same_parent: bool

Returns if the parent is the same class as itself.

def root(self) -> sqlglot.expressions.Expression:
377    def root(self) -> Expression:
378        """
379        Returns the root expression of this tree.
380        """
381        expression = self
382        while expression.parent:
383            expression = expression.parent
384        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
386    def walk(self, bfs=True, prune=None):
387        """
388        Returns a generator object which visits all nodes in this tree.
389
390        Args:
391            bfs (bool): if set to True the BFS traversal order will be applied,
392                otherwise the DFS traversal will be used instead.
393            prune ((node, parent, arg_key) -> bool): callable that returns True if
394                the generator should stop traversing this branch of the tree.
395
396        Returns:
397            the generator object.
398        """
399        if bfs:
400            yield from self.bfs(prune=prune)
401        else:
402            yield from self.dfs(prune=prune)

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs(self, parent=None, key=None, prune=None):
404    def dfs(self, parent=None, key=None, prune=None):
405        """
406        Returns a generator object which visits all nodes in this tree in
407        the DFS (Depth-first) order.
408
409        Returns:
410            The generator object.
411        """
412        parent = parent or self.parent
413        yield self, parent, key
414        if prune and prune(self, parent, key):
415            return
416
417        for k, v in self.iter_expressions():
418            yield from v.dfs(self, k, prune)

Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.

Returns:

The generator object.

def bfs(self, prune=None):
420    def bfs(self, prune=None):
421        """
422        Returns a generator object which visits all nodes in this tree in
423        the BFS (Breadth-first) order.
424
425        Returns:
426            The generator object.
427        """
428        queue = deque([(self, self.parent, None)])
429
430        while queue:
431            item, parent, key = queue.popleft()
432
433            yield item, parent, key
434            if prune and prune(item, parent, key):
435                continue
436
437            for k, v in item.iter_expressions():
438                queue.append((v, item, k))

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self):
440    def unnest(self):
441        """
442        Returns the first non parenthesis child or self.
443        """
444        expression = self
445        while type(expression) is Paren:
446            expression = expression.this
447        return expression

Returns the first non parenthesis child or self.

def unalias(self):
449    def unalias(self):
450        """
451        Returns the inner expression if this is an Alias.
452        """
453        if isinstance(self, Alias):
454            return self.this
455        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
457    def unnest_operands(self):
458        """
459        Returns unnested operands as a tuple.
460        """
461        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
463    def flatten(self, unnest=True):
464        """
465        Returns a generator which yields child nodes who's parents are the same class.
466
467        A AND B AND C -> [A, B, C]
468        """
469        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
470            if not type(node) is self.__class__:
471                yield node.unnest() if unnest else node

Returns a generator which yields child nodes who's parents are the same class.

A AND B AND C -> [A, B, C]

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
479    def sql(self, dialect: DialectType = None, **opts) -> str:
480        """
481        Returns SQL string representation of this tree.
482
483        Args:
484            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
485            opts: other `sqlglot.generator.Generator` options.
486
487        Returns:
488            The SQL string.
489        """
490        from sqlglot.dialects import Dialect
491
492        return Dialect.get_or_raise(dialect)().generate(self, **opts)

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform(self, fun, *args, copy=True, **kwargs):
518    def transform(self, fun, *args, copy=True, **kwargs):
519        """
520        Recursively visits all tree nodes (excluding already transformed ones)
521        and applies the given transformation function to each node.
522
523        Args:
524            fun (function): a function which takes a node as an argument and returns a
525                new transformed node or the same node without modifications. If the function
526                returns None, then the corresponding node will be removed from the syntax tree.
527            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
528                modified in place.
529
530        Returns:
531            The transformed tree.
532        """
533        node = self.copy() if copy else self
534        new_node = fun(node, *args, **kwargs)
535
536        if new_node is None or not isinstance(new_node, Expression):
537            return new_node
538        if new_node is not node:
539            new_node.parent = node.parent
540            return new_node
541
542        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
543        return new_node

Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression):
553    def replace(self, expression):
554        """
555        Swap out this expression with a new expression.
556
557        For example::
558
559            >>> tree = Select().select("x").from_("tbl")
560            >>> tree.find(Column).replace(Column(this="y"))
561            (COLUMN this: y)
562            >>> tree.sql()
563            'SELECT y FROM tbl'
564
565        Args:
566            expression: new node
567
568        Returns:
569            The new expression or expressions.
570        """
571        if not self.parent:
572            return expression
573
574        parent = self.parent
575        self.parent = None
576
577        replace_children(parent, lambda child: expression if child is self else child)
578        return expression

Swap out this expression with a new expression.

For example::

>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression: new node
Returns:

The new expression or expressions.

def pop(self: ~E) -> ~E:
580    def pop(self: E) -> E:
581        """
582        Remove this expression from its AST.
583
584        Returns:
585            The popped expression.
586        """
587        self.replace(None)
588        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_: Type[~E]) -> ~E:
590    def assert_is(self, type_: t.Type[E]) -> E:
591        """
592        Assert that this `Expression` is an instance of `type_`.
593
594        If it is NOT an instance of `type_`, this raises an assertion error.
595        Otherwise, this returns this expression.
596
597        Examples:
598            This is useful for type security in chained expressions:
599
600            >>> import sqlglot
601            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
602            'SELECT x, z FROM y'
603        """
604        assert isinstance(self, type_)
605        return self

Assert that this Expression is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Optional[Sequence] = None) -> List[str]:
607    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
608        """
609        Checks if this expression is valid (e.g. all mandatory args are set).
610
611        Args:
612            args: a sequence of values that were used to instantiate a Func expression. This is used
613                to check that the provided arguments don't exceed the function argument limit.
614
615        Returns:
616            A list of error messages for all possible errors that were found.
617        """
618        errors: t.List[str] = []
619
620        for k in self.args:
621            if k not in self.arg_types:
622                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
623        for k, mandatory in self.arg_types.items():
624            v = self.args.get(k)
625            if mandatory and (v is None or (isinstance(v, list) and not v)):
626                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
627
628        if (
629            args
630            and isinstance(self, Func)
631            and len(args) > len(self.arg_types)
632            and not self.is_var_len_args
633        ):
634            errors.append(
635                f"The number of provided arguments ({len(args)}) is greater than "
636                f"the maximum number of supported arguments ({len(self.arg_types)})"
637            )
638
639        return errors

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def dump(self):
641    def dump(self):
642        """
643        Dump this Expression to a JSON-serializable dict.
644        """
645        from sqlglot.serde import dump
646
647        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
649    @classmethod
650    def load(cls, obj):
651        """
652        Load a dict (as returned by `Expression.dump`) into an Expression instance.
653        """
654        from sqlglot.serde import load
655
656        return load(obj)

Load a dict (as returned by Expression.dump) into an Expression instance.

IntoType = typing.Union[str, typing.Type[sqlglot.expressions.Expression], typing.Collection[typing.Union[str, typing.Type[sqlglot.expressions.Expression]]]]
ExpOrStr = typing.Union[str, sqlglot.expressions.Expression]
class Condition(Expression):
667class Condition(Expression):
668    def and_(
669        self,
670        *expressions: t.Optional[ExpOrStr],
671        dialect: DialectType = None,
672        copy: bool = True,
673        **opts,
674    ) -> Condition:
675        """
676        AND this condition with one or multiple expressions.
677
678        Example:
679            >>> condition("x=1").and_("y=1").sql()
680            'x = 1 AND y = 1'
681
682        Args:
683            *expressions: the SQL code strings to parse.
684                If an `Expression` instance is passed, it will be used as-is.
685            dialect: the dialect used to parse the input expression.
686            copy: whether or not to copy the involved expressions (only applies to Expressions).
687            opts: other options to use to parse the input expressions.
688
689        Returns:
690            The new And condition.
691        """
692        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
693
694    def or_(
695        self,
696        *expressions: t.Optional[ExpOrStr],
697        dialect: DialectType = None,
698        copy: bool = True,
699        **opts,
700    ) -> Condition:
701        """
702        OR this condition with one or multiple expressions.
703
704        Example:
705            >>> condition("x=1").or_("y=1").sql()
706            'x = 1 OR y = 1'
707
708        Args:
709            *expressions: the SQL code strings to parse.
710                If an `Expression` instance is passed, it will be used as-is.
711            dialect: the dialect used to parse the input expression.
712            copy: whether or not to copy the involved expressions (only applies to Expressions).
713            opts: other options to use to parse the input expressions.
714
715        Returns:
716            The new Or condition.
717        """
718        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
719
720    def not_(self, copy: bool = True):
721        """
722        Wrap this condition with NOT.
723
724        Example:
725            >>> condition("x=1").not_().sql()
726            'NOT x = 1'
727
728        Args:
729            copy: whether or not to copy this object.
730
731        Returns:
732            The new Not instance.
733        """
734        return not_(self, copy=copy)
735
736    def as_(
737        self,
738        alias: str | Identifier,
739        quoted: t.Optional[bool] = None,
740        dialect: DialectType = None,
741        copy: bool = True,
742        **opts,
743    ) -> Alias:
744        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
745
746    def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
747        this = self.copy()
748        other = convert(other, copy=True)
749        if not isinstance(this, klass) and not isinstance(other, klass):
750            this = _wrap(this, Binary)
751            other = _wrap(other, Binary)
752        if reverse:
753            return klass(this=other, expression=this)
754        return klass(this=this, expression=other)
755
756    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
757        return Bracket(
758            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
759        )
760
761    def isin(
762        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
763    ) -> In:
764        return In(
765            this=_maybe_copy(self, copy),
766            expressions=[convert(e, copy=copy) for e in expressions],
767            query=maybe_parse(query, copy=copy, **opts) if query else None,
768        )
769
770    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
771        return Between(
772            this=_maybe_copy(self, copy),
773            low=convert(low, copy=copy, **opts),
774            high=convert(high, copy=copy, **opts),
775        )
776
777    def is_(self, other: ExpOrStr) -> Is:
778        return self._binop(Is, other)
779
780    def like(self, other: ExpOrStr) -> Like:
781        return self._binop(Like, other)
782
783    def ilike(self, other: ExpOrStr) -> ILike:
784        return self._binop(ILike, other)
785
786    def eq(self, other: t.Any) -> EQ:
787        return self._binop(EQ, other)
788
789    def neq(self, other: t.Any) -> NEQ:
790        return self._binop(NEQ, other)
791
792    def rlike(self, other: ExpOrStr) -> RegexpLike:
793        return self._binop(RegexpLike, other)
794
795    def __lt__(self, other: t.Any) -> LT:
796        return self._binop(LT, other)
797
798    def __le__(self, other: t.Any) -> LTE:
799        return self._binop(LTE, other)
800
801    def __gt__(self, other: t.Any) -> GT:
802        return self._binop(GT, other)
803
804    def __ge__(self, other: t.Any) -> GTE:
805        return self._binop(GTE, other)
806
807    def __add__(self, other: t.Any) -> Add:
808        return self._binop(Add, other)
809
810    def __radd__(self, other: t.Any) -> Add:
811        return self._binop(Add, other, reverse=True)
812
813    def __sub__(self, other: t.Any) -> Sub:
814        return self._binop(Sub, other)
815
816    def __rsub__(self, other: t.Any) -> Sub:
817        return self._binop(Sub, other, reverse=True)
818
819    def __mul__(self, other: t.Any) -> Mul:
820        return self._binop(Mul, other)
821
822    def __rmul__(self, other: t.Any) -> Mul:
823        return self._binop(Mul, other, reverse=True)
824
825    def __truediv__(self, other: t.Any) -> Div:
826        return self._binop(Div, other)
827
828    def __rtruediv__(self, other: t.Any) -> Div:
829        return self._binop(Div, other, reverse=True)
830
831    def __floordiv__(self, other: t.Any) -> IntDiv:
832        return self._binop(IntDiv, other)
833
834    def __rfloordiv__(self, other: t.Any) -> IntDiv:
835        return self._binop(IntDiv, other, reverse=True)
836
837    def __mod__(self, other: t.Any) -> Mod:
838        return self._binop(Mod, other)
839
840    def __rmod__(self, other: t.Any) -> Mod:
841        return self._binop(Mod, other, reverse=True)
842
843    def __pow__(self, other: t.Any) -> Pow:
844        return self._binop(Pow, other)
845
846    def __rpow__(self, other: t.Any) -> Pow:
847        return self._binop(Pow, other, reverse=True)
848
849    def __and__(self, other: t.Any) -> And:
850        return self._binop(And, other)
851
852    def __rand__(self, other: t.Any) -> And:
853        return self._binop(And, other, reverse=True)
854
855    def __or__(self, other: t.Any) -> Or:
856        return self._binop(Or, other)
857
858    def __ror__(self, other: t.Any) -> Or:
859        return self._binop(Or, other, reverse=True)
860
861    def __neg__(self) -> Neg:
862        return Neg(this=_wrap(self.copy(), Binary))
863
864    def __invert__(self) -> Not:
865        return not_(self.copy())
def and_( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
668    def and_(
669        self,
670        *expressions: t.Optional[ExpOrStr],
671        dialect: DialectType = None,
672        copy: bool = True,
673        **opts,
674    ) -> Condition:
675        """
676        AND this condition with one or multiple expressions.
677
678        Example:
679            >>> condition("x=1").and_("y=1").sql()
680            'x = 1 AND y = 1'
681
682        Args:
683            *expressions: the SQL code strings to parse.
684                If an `Expression` instance is passed, it will be used as-is.
685            dialect: the dialect used to parse the input expression.
686            copy: whether or not to copy the involved expressions (only applies to Expressions).
687            opts: other options to use to parse the input expressions.
688
689        Returns:
690            The new And condition.
691        """
692        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy the involved expressions (only applies to Expressions).
  • opts: other options to use to parse the input expressions.
Returns:

The new And condition.

def or_( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
694    def or_(
695        self,
696        *expressions: t.Optional[ExpOrStr],
697        dialect: DialectType = None,
698        copy: bool = True,
699        **opts,
700    ) -> Condition:
701        """
702        OR this condition with one or multiple expressions.
703
704        Example:
705            >>> condition("x=1").or_("y=1").sql()
706            'x = 1 OR y = 1'
707
708        Args:
709            *expressions: the SQL code strings to parse.
710                If an `Expression` instance is passed, it will be used as-is.
711            dialect: the dialect used to parse the input expression.
712            copy: whether or not to copy the involved expressions (only applies to Expressions).
713            opts: other options to use to parse the input expressions.
714
715        Returns:
716            The new Or condition.
717        """
718        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy the involved expressions (only applies to Expressions).
  • opts: other options to use to parse the input expressions.
Returns:

The new Or condition.

def not_(self, copy: bool = True):
720    def not_(self, copy: bool = True):
721        """
722        Wrap this condition with NOT.
723
724        Example:
725            >>> condition("x=1").not_().sql()
726            'NOT x = 1'
727
728        Args:
729            copy: whether or not to copy this object.
730
731        Returns:
732            The new Not instance.
733        """
734        return not_(self, copy=copy)

Wrap this condition with NOT.

Example:
>>> condition("x=1").not_().sql()
'NOT x = 1'
Arguments:
  • copy: whether or not to copy this object.
Returns:

The new Not instance.

def as_( self, alias: str | sqlglot.expressions.Identifier, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Alias:
736    def as_(
737        self,
738        alias: str | Identifier,
739        quoted: t.Optional[bool] = None,
740        dialect: DialectType = None,
741        copy: bool = True,
742        **opts,
743    ) -> Alias:
744        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
761    def isin(
762        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
763    ) -> In:
764        return In(
765            this=_maybe_copy(self, copy),
766            expressions=[convert(e, copy=copy) for e in expressions],
767            query=maybe_parse(query, copy=copy, **opts) if query else None,
768        )
def between( self, low: Any, high: Any, copy: bool = True, **opts) -> sqlglot.expressions.Between:
770    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
771        return Between(
772            this=_maybe_copy(self, copy),
773            low=convert(low, copy=copy, **opts),
774            high=convert(high, copy=copy, **opts),
775        )
def is_( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Is:
777    def is_(self, other: ExpOrStr) -> Is:
778        return self._binop(Is, other)
def like( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Like:
780    def like(self, other: ExpOrStr) -> Like:
781        return self._binop(Like, other)
def ilike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.ILike:
783    def ilike(self, other: ExpOrStr) -> ILike:
784        return self._binop(ILike, other)
def eq(self, other: Any) -> sqlglot.expressions.EQ:
786    def eq(self, other: t.Any) -> EQ:
787        return self._binop(EQ, other)
def neq(self, other: Any) -> sqlglot.expressions.NEQ:
789    def neq(self, other: t.Any) -> NEQ:
790        return self._binop(NEQ, other)
def rlike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.RegexpLike:
792    def rlike(self, other: ExpOrStr) -> RegexpLike:
793        return self._binop(RegexpLike, other)
key = 'condition'
class Predicate(Condition):
868class Predicate(Condition):
869    """Relationships like x = y, x > 1, x >= y."""

Relationships like x = y, x > 1, x >= y.

key = 'predicate'
class DerivedTable(Expression):
872class DerivedTable(Expression):
873    @property
874    def alias_column_names(self) -> t.List[str]:
875        table_alias = self.args.get("alias")
876        if not table_alias:
877            return []
878        return [c.name for c in table_alias.args.get("columns") or []]
879
880    @property
881    def selects(self):
882        return self.this.selects if isinstance(self.this, Subqueryable) else []
883
884    @property
885    def named_selects(self):
886        return [select.output_name for select in self.selects]
alias_column_names: List[str]
selects
named_selects
key = 'derivedtable'
class Unionable(Expression):
889class Unionable(Expression):
890    def union(
891        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
892    ) -> Unionable:
893        """
894        Builds a UNION expression.
895
896        Example:
897            >>> import sqlglot
898            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
899            'SELECT * FROM foo UNION SELECT * FROM bla'
900
901        Args:
902            expression: the SQL code string.
903                If an `Expression` instance is passed, it will be used as-is.
904            distinct: set the DISTINCT flag if and only if this is true.
905            dialect: the dialect used to parse the input expression.
906            opts: other options to use to parse the input expressions.
907
908        Returns:
909            The new Union expression.
910        """
911        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
912
913    def intersect(
914        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
915    ) -> Unionable:
916        """
917        Builds an INTERSECT expression.
918
919        Example:
920            >>> import sqlglot
921            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
922            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
923
924        Args:
925            expression: the SQL code string.
926                If an `Expression` instance is passed, it will be used as-is.
927            distinct: set the DISTINCT flag if and only if this is true.
928            dialect: the dialect used to parse the input expression.
929            opts: other options to use to parse the input expressions.
930
931        Returns:
932            The new Intersect expression.
933        """
934        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
935
936    def except_(
937        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
938    ) -> Unionable:
939        """
940        Builds an EXCEPT expression.
941
942        Example:
943            >>> import sqlglot
944            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
945            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
946
947        Args:
948            expression: the SQL code string.
949                If an `Expression` instance is passed, it will be used as-is.
950            distinct: set the DISTINCT flag if and only if this is true.
951            dialect: the dialect used to parse the input expression.
952            opts: other options to use to parse the input expressions.
953
954        Returns:
955            The new Except expression.
956        """
957        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
890    def union(
891        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
892    ) -> Unionable:
893        """
894        Builds a UNION expression.
895
896        Example:
897            >>> import sqlglot
898            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
899            'SELECT * FROM foo UNION SELECT * FROM bla'
900
901        Args:
902            expression: the SQL code string.
903                If an `Expression` instance is passed, it will be used as-is.
904            distinct: set the DISTINCT flag if and only if this is true.
905            dialect: the dialect used to parse the input expression.
906            opts: other options to use to parse the input expressions.
907
908        Returns:
909            The new Union expression.
910        """
911        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Union expression.

def intersect( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
913    def intersect(
914        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
915    ) -> Unionable:
916        """
917        Builds an INTERSECT expression.
918
919        Example:
920            >>> import sqlglot
921            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
922            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
923
924        Args:
925            expression: the SQL code string.
926                If an `Expression` instance is passed, it will be used as-is.
927            distinct: set the DISTINCT flag if and only if this is true.
928            dialect: the dialect used to parse the input expression.
929            opts: other options to use to parse the input expressions.
930
931        Returns:
932            The new Intersect expression.
933        """
934        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Intersect expression.

def except_( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
936    def except_(
937        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
938    ) -> Unionable:
939        """
940        Builds an EXCEPT expression.
941
942        Example:
943            >>> import sqlglot
944            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
945            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
946
947        Args:
948            expression: the SQL code string.
949                If an `Expression` instance is passed, it will be used as-is.
950            distinct: set the DISTINCT flag if and only if this is true.
951            dialect: the dialect used to parse the input expression.
952            opts: other options to use to parse the input expressions.
953
954        Returns:
955            The new Except expression.
956        """
957        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Except expression.

key = 'unionable'
class UDTF(DerivedTable, Unionable):
960class UDTF(DerivedTable, Unionable):
961    @property
962    def selects(self):
963        alias = self.args.get("alias")
964        return alias.columns if alias else []
selects
key = 'udtf'
class Cache(Expression):
967class Cache(Expression):
968    arg_types = {
969        "with": False,
970        "this": True,
971        "lazy": False,
972        "options": False,
973        "expression": False,
974    }
arg_types = {'with': False, 'this': True, 'lazy': False, 'options': False, 'expression': False}
key = 'cache'
class Uncache(Expression):
977class Uncache(Expression):
978    arg_types = {"this": True, "exists": False}
arg_types = {'this': True, 'exists': False}
key = 'uncache'
class Create(Expression):
981class Create(Expression):
982    arg_types = {
983        "with": False,
984        "this": True,
985        "kind": True,
986        "expression": False,
987        "exists": False,
988        "properties": False,
989        "replace": False,
990        "unique": False,
991        "indexes": False,
992        "no_schema_binding": False,
993        "begin": False,
994        "clone": False,
995    }
arg_types = {'with': False, 'this': True, 'kind': True, 'expression': False, 'exists': False, 'properties': False, 'replace': False, 'unique': False, 'indexes': False, 'no_schema_binding': False, 'begin': False, 'clone': False}
key = 'create'
class Clone(Expression):
 999class Clone(Expression):
1000    arg_types = {
1001        "this": True,
1002        "when": False,
1003        "kind": False,
1004        "expression": False,
1005    }
arg_types = {'this': True, 'when': False, 'kind': False, 'expression': False}
key = 'clone'
class Describe(Expression):
1008class Describe(Expression):
1009    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'describe'
class Pragma(Expression):
1012class Pragma(Expression):
1013    pass
key = 'pragma'
class Set(Expression):
1016class Set(Expression):
1017    arg_types = {"expressions": False, "unset": False, "tag": False}
arg_types = {'expressions': False, 'unset': False, 'tag': False}
key = 'set'
class SetItem(Expression):
1020class SetItem(Expression):
1021    arg_types = {
1022        "this": False,
1023        "expressions": False,
1024        "kind": False,
1025        "collate": False,  # MySQL SET NAMES statement
1026        "global": False,
1027    }
arg_types = {'this': False, 'expressions': False, 'kind': False, 'collate': False, 'global': False}
key = 'setitem'
class Show(Expression):
1030class Show(Expression):
1031    arg_types = {
1032        "this": True,
1033        "target": False,
1034        "offset": False,
1035        "limit": False,
1036        "like": False,
1037        "where": False,
1038        "db": False,
1039        "full": False,
1040        "mutex": False,
1041        "query": False,
1042        "channel": False,
1043        "global": False,
1044        "log": False,
1045        "position": False,
1046        "types": False,
1047    }
arg_types = {'this': True, 'target': False, 'offset': False, 'limit': False, 'like': False, 'where': False, 'db': False, 'full': False, 'mutex': False, 'query': False, 'channel': False, 'global': False, 'log': False, 'position': False, 'types': False}
key = 'show'
class UserDefinedFunction(Expression):
1050class UserDefinedFunction(Expression):
1051    arg_types = {"this": True, "expressions": False, "wrapped": False}
arg_types = {'this': True, 'expressions': False, 'wrapped': False}
key = 'userdefinedfunction'
class CharacterSet(Expression):
1054class CharacterSet(Expression):
1055    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'characterset'
class With(Expression):
1058class With(Expression):
1059    arg_types = {"expressions": True, "recursive": False}
1060
1061    @property
1062    def recursive(self) -> bool:
1063        return bool(self.args.get("recursive"))
arg_types = {'expressions': True, 'recursive': False}
recursive: bool
key = 'with'
class WithinGroup(Expression):
1066class WithinGroup(Expression):
1067    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'withingroup'
class CTE(DerivedTable):
1070class CTE(DerivedTable):
1071    arg_types = {"this": True, "alias": True}
arg_types = {'this': True, 'alias': True}
key = 'cte'
class TableAlias(Expression):
1074class TableAlias(Expression):
1075    arg_types = {"this": False, "columns": False}
1076
1077    @property
1078    def columns(self):
1079        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns
key = 'tablealias'
class BitString(Condition):
1082class BitString(Condition):
1083    pass
key = 'bitstring'
class HexString(Condition):
1086class HexString(Condition):
1087    pass
key = 'hexstring'
class ByteString(Condition):
1090class ByteString(Condition):
1091    pass
key = 'bytestring'
class RawString(Condition):
1094class RawString(Condition):
1095    pass
key = 'rawstring'
class Column(Condition):
1098class Column(Condition):
1099    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1100
1101    @property
1102    def table(self) -> str:
1103        return self.text("table")
1104
1105    @property
1106    def db(self) -> str:
1107        return self.text("db")
1108
1109    @property
1110    def catalog(self) -> str:
1111        return self.text("catalog")
1112
1113    @property
1114    def output_name(self) -> str:
1115        return self.name
1116
1117    @property
1118    def parts(self) -> t.List[Identifier]:
1119        """Return the parts of a column in order catalog, db, table, name."""
1120        return [
1121            t.cast(Identifier, self.args[part])
1122            for part in ("catalog", "db", "table", "this")
1123            if self.args.get(part)
1124        ]
1125
1126    def to_dot(self) -> Dot:
1127        """Converts the column into a dot expression."""
1128        parts = self.parts
1129        parent = self.parent
1130
1131        while parent:
1132            if isinstance(parent, Dot):
1133                parts.append(parent.expression)
1134            parent = parent.parent
1135
1136        return Dot.build(parts)
arg_types = {'this': True, 'table': False, 'db': False, 'catalog': False, 'join_mark': False}
table: str
db: str
catalog: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''

Return the parts of a column in order catalog, db, table, name.

def to_dot(self) -> sqlglot.expressions.Dot:
1126    def to_dot(self) -> Dot:
1127        """Converts the column into a dot expression."""
1128        parts = self.parts
1129        parent = self.parent
1130
1131        while parent:
1132            if isinstance(parent, Dot):
1133                parts.append(parent.expression)
1134            parent = parent.parent
1135
1136        return Dot.build(parts)

Converts the column into a dot expression.

key = 'column'
class ColumnPosition(Expression):
1139class ColumnPosition(Expression):
1140    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key = 'columnposition'
class ColumnDef(Expression):
1143class ColumnDef(Expression):
1144    arg_types = {
1145        "this": True,
1146        "kind": False,
1147        "constraints": False,
1148        "exists": False,
1149        "position": False,
1150    }
1151
1152    @property
1153    def constraints(self) -> t.List[ColumnConstraint]:
1154        return self.args.get("constraints") or []
arg_types = {'this': True, 'kind': False, 'constraints': False, 'exists': False, 'position': False}
key = 'columndef'
class AlterColumn(Expression):
1157class AlterColumn(Expression):
1158    arg_types = {
1159        "this": True,
1160        "dtype": False,
1161        "collate": False,
1162        "using": False,
1163        "default": False,
1164        "drop": False,
1165    }
arg_types = {'this': True, 'dtype': False, 'collate': False, 'using': False, 'default': False, 'drop': False}
key = 'altercolumn'
class RenameTable(Expression):
1168class RenameTable(Expression):
1169    pass
key = 'renametable'
class Comment(Expression):
1172class Comment(Expression):
1173    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
arg_types = {'this': True, 'kind': True, 'expression': True, 'exists': False}
key = 'comment'
class MergeTreeTTLAction(Expression):
1177class MergeTreeTTLAction(Expression):
1178    arg_types = {
1179        "this": True,
1180        "delete": False,
1181        "recompress": False,
1182        "to_disk": False,
1183        "to_volume": False,
1184    }
arg_types = {'this': True, 'delete': False, 'recompress': False, 'to_disk': False, 'to_volume': False}
key = 'mergetreettlaction'
class MergeTreeTTL(Expression):
1188class MergeTreeTTL(Expression):
1189    arg_types = {
1190        "expressions": True,
1191        "where": False,
1192        "group": False,
1193        "aggregates": False,
1194    }
arg_types = {'expressions': True, 'where': False, 'group': False, 'aggregates': False}
key = 'mergetreettl'
class ColumnConstraint(Expression):
1197class ColumnConstraint(Expression):
1198    arg_types = {"this": False, "kind": True}
1199
1200    @property
1201    def kind(self) -> ColumnConstraintKind:
1202        return self.args["kind"]
arg_types = {'this': False, 'kind': True}
key = 'columnconstraint'
class ColumnConstraintKind(Expression):
1205class ColumnConstraintKind(Expression):
1206    pass
key = 'columnconstraintkind'
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1209class AutoIncrementColumnConstraint(ColumnConstraintKind):
1210    pass
key = 'autoincrementcolumnconstraint'
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1213class CaseSpecificColumnConstraint(ColumnConstraintKind):
1214    arg_types = {"not_": True}
arg_types = {'not_': True}
key = 'casespecificcolumnconstraint'
class CharacterSetColumnConstraint(ColumnConstraintKind):
1217class CharacterSetColumnConstraint(ColumnConstraintKind):
1218    arg_types = {"this": True}
arg_types = {'this': True}
key = 'charactersetcolumnconstraint'
class CheckColumnConstraint(ColumnConstraintKind):
1221class CheckColumnConstraint(ColumnConstraintKind):
1222    pass
key = 'checkcolumnconstraint'
class CollateColumnConstraint(ColumnConstraintKind):
1225class CollateColumnConstraint(ColumnConstraintKind):
1226    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1229class CommentColumnConstraint(ColumnConstraintKind):
1230    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1233class CompressColumnConstraint(ColumnConstraintKind):
1234    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1237class DateFormatColumnConstraint(ColumnConstraintKind):
1238    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1241class DefaultColumnConstraint(ColumnConstraintKind):
1242    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1245class EncodeColumnConstraint(ColumnConstraintKind):
1246    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1249class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1250    # this: True -> ALWAYS, this: False -> BY DEFAULT
1251    arg_types = {
1252        "this": False,
1253        "expression": False,
1254        "on_null": False,
1255        "start": False,
1256        "increment": False,
1257        "minvalue": False,
1258        "maxvalue": False,
1259        "cycle": False,
1260    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class InlineLengthColumnConstraint(ColumnConstraintKind):
1263class InlineLengthColumnConstraint(ColumnConstraintKind):
1264    pass
key = 'inlinelengthcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1267class NotNullColumnConstraint(ColumnConstraintKind):
1268    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1272class OnUpdateColumnConstraint(ColumnConstraintKind):
1273    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1276class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1277    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1280class TitleColumnConstraint(ColumnConstraintKind):
1281    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1284class UniqueColumnConstraint(ColumnConstraintKind):
1285    arg_types = {"this": False}
arg_types = {'this': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1288class UppercaseColumnConstraint(ColumnConstraintKind):
1289    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1292class PathColumnConstraint(ColumnConstraintKind):
1293    pass
key = 'pathcolumnconstraint'
class Constraint(Expression):
1296class Constraint(Expression):
1297    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1300class Delete(Expression):
1301    arg_types = {
1302        "with": False,
1303        "this": False,
1304        "using": False,
1305        "where": False,
1306        "returning": False,
1307        "limit": False,
1308    }
1309
1310    def delete(
1311        self,
1312        table: ExpOrStr,
1313        dialect: DialectType = None,
1314        copy: bool = True,
1315        **opts,
1316    ) -> Delete:
1317        """
1318        Create a DELETE expression or replace the table on an existing DELETE expression.
1319
1320        Example:
1321            >>> delete("tbl").sql()
1322            'DELETE FROM tbl'
1323
1324        Args:
1325            table: the table from which to delete.
1326            dialect: the dialect used to parse the input expression.
1327            copy: if `False`, modify this expression instance in-place.
1328            opts: other options to use to parse the input expressions.
1329
1330        Returns:
1331            Delete: the modified expression.
1332        """
1333        return _apply_builder(
1334            expression=table,
1335            instance=self,
1336            arg="this",
1337            dialect=dialect,
1338            into=Table,
1339            copy=copy,
1340            **opts,
1341        )
1342
1343    def where(
1344        self,
1345        *expressions: t.Optional[ExpOrStr],
1346        append: bool = True,
1347        dialect: DialectType = None,
1348        copy: bool = True,
1349        **opts,
1350    ) -> Delete:
1351        """
1352        Append to or set the WHERE expressions.
1353
1354        Example:
1355            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1356            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1357
1358        Args:
1359            *expressions: the SQL code strings to parse.
1360                If an `Expression` instance is passed, it will be used as-is.
1361                Multiple expressions are combined with an AND operator.
1362            append: if `True`, AND the new expressions to any existing expression.
1363                Otherwise, this resets the expression.
1364            dialect: the dialect used to parse the input expressions.
1365            copy: if `False`, modify this expression instance in-place.
1366            opts: other options to use to parse the input expressions.
1367
1368        Returns:
1369            Delete: the modified expression.
1370        """
1371        return _apply_conjunction_builder(
1372            *expressions,
1373            instance=self,
1374            arg="where",
1375            append=append,
1376            into=Where,
1377            dialect=dialect,
1378            copy=copy,
1379            **opts,
1380        )
1381
1382    def returning(
1383        self,
1384        expression: ExpOrStr,
1385        dialect: DialectType = None,
1386        copy: bool = True,
1387        **opts,
1388    ) -> Delete:
1389        """
1390        Set the RETURNING expression. Not supported by all dialects.
1391
1392        Example:
1393            >>> delete("tbl").returning("*", dialect="postgres").sql()
1394            'DELETE FROM tbl RETURNING *'
1395
1396        Args:
1397            expression: the SQL code strings to parse.
1398                If an `Expression` instance is passed, it will be used as-is.
1399            dialect: the dialect used to parse the input expressions.
1400            copy: if `False`, modify this expression instance in-place.
1401            opts: other options to use to parse the input expressions.
1402
1403        Returns:
1404            Delete: the modified expression.
1405        """
1406        return _apply_builder(
1407            expression=expression,
1408            instance=self,
1409            arg="returning",
1410            prefix="RETURNING",
1411            dialect=dialect,
1412            copy=copy,
1413            into=Returning,
1414            **opts,
1415        )
arg_types = {'with': False, 'this': False, 'using': False, 'where': False, 'returning': False, 'limit': False}
def delete( self, table: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1310    def delete(
1311        self,
1312        table: ExpOrStr,
1313        dialect: DialectType = None,
1314        copy: bool = True,
1315        **opts,
1316    ) -> Delete:
1317        """
1318        Create a DELETE expression or replace the table on an existing DELETE expression.
1319
1320        Example:
1321            >>> delete("tbl").sql()
1322            'DELETE FROM tbl'
1323
1324        Args:
1325            table: the table from which to delete.
1326            dialect: the dialect used to parse the input expression.
1327            copy: if `False`, modify this expression instance in-place.
1328            opts: other options to use to parse the input expressions.
1329
1330        Returns:
1331            Delete: the modified expression.
1332        """
1333        return _apply_builder(
1334            expression=table,
1335            instance=self,
1336            arg="this",
1337            dialect=dialect,
1338            into=Table,
1339            copy=copy,
1340            **opts,
1341        )

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1343    def where(
1344        self,
1345        *expressions: t.Optional[ExpOrStr],
1346        append: bool = True,
1347        dialect: DialectType = None,
1348        copy: bool = True,
1349        **opts,
1350    ) -> Delete:
1351        """
1352        Append to or set the WHERE expressions.
1353
1354        Example:
1355            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1356            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1357
1358        Args:
1359            *expressions: the SQL code strings to parse.
1360                If an `Expression` instance is passed, it will be used as-is.
1361                Multiple expressions are combined with an AND operator.
1362            append: if `True`, AND the new expressions to any existing expression.
1363                Otherwise, this resets the expression.
1364            dialect: the dialect used to parse the input expressions.
1365            copy: if `False`, modify this expression instance in-place.
1366            opts: other options to use to parse the input expressions.
1367
1368        Returns:
1369            Delete: the modified expression.
1370        """
1371        return _apply_conjunction_builder(
1372            *expressions,
1373            instance=self,
1374            arg="where",
1375            append=append,
1376            into=Where,
1377            dialect=dialect,
1378            copy=copy,
1379            **opts,
1380        )

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def returning( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1382    def returning(
1383        self,
1384        expression: ExpOrStr,
1385        dialect: DialectType = None,
1386        copy: bool = True,
1387        **opts,
1388    ) -> Delete:
1389        """
1390        Set the RETURNING expression. Not supported by all dialects.
1391
1392        Example:
1393            >>> delete("tbl").returning("*", dialect="postgres").sql()
1394            'DELETE FROM tbl RETURNING *'
1395
1396        Args:
1397            expression: the SQL code strings to parse.
1398                If an `Expression` instance is passed, it will be used as-is.
1399            dialect: the dialect used to parse the input expressions.
1400            copy: if `False`, modify this expression instance in-place.
1401            opts: other options to use to parse the input expressions.
1402
1403        Returns:
1404            Delete: the modified expression.
1405        """
1406        return _apply_builder(
1407            expression=expression,
1408            instance=self,
1409            arg="returning",
1410            prefix="RETURNING",
1411            dialect=dialect,
1412            copy=copy,
1413            into=Returning,
1414            **opts,
1415        )

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

key = 'delete'
class Drop(Expression):
1418class Drop(Expression):
1419    arg_types = {
1420        "this": False,
1421        "kind": False,
1422        "exists": False,
1423        "temporary": False,
1424        "materialized": False,
1425        "cascade": False,
1426        "constraints": False,
1427        "purge": False,
1428    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1431class Filter(Expression):
1432    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1435class Check(Expression):
1436    pass
key = 'check'
class Directory(Expression):
1439class Directory(Expression):
1440    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1441    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1444class ForeignKey(Expression):
1445    arg_types = {
1446        "expressions": True,
1447        "reference": False,
1448        "delete": False,
1449        "update": False,
1450    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class PrimaryKey(Expression):
1453class PrimaryKey(Expression):
1454    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1459class Into(Expression):
1460    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1463class From(Expression):
1464    @property
1465    def name(self) -> str:
1466        return self.this.name
1467
1468    @property
1469    def alias_or_name(self) -> str:
1470        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1473class Having(Expression):
1474    pass
key = 'having'
class Hint(Expression):
1477class Hint(Expression):
1478    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1481class JoinHint(Expression):
1482    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1485class Identifier(Expression):
1486    arg_types = {"this": True, "quoted": False}
1487
1488    @property
1489    def quoted(self) -> bool:
1490        return bool(self.args.get("quoted"))
1491
1492    @property
1493    def hashable_args(self) -> t.Any:
1494        if self.quoted and any(char.isupper() for char in self.this):
1495            return (self.this, self.quoted)
1496        return self.this.lower()
1497
1498    @property
1499    def output_name(self) -> str:
1500        return self.name
arg_types = {'this': True, 'quoted': False}
quoted: bool
hashable_args: Any
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'identifier'
class Index(Expression):
1503class Index(Expression):
1504    arg_types = {
1505        "this": False,
1506        "table": False,
1507        "using": False,
1508        "where": False,
1509        "columns": False,
1510        "unique": False,
1511        "primary": False,
1512        "amp": False,  # teradata
1513        "partition_by": False,  # teradata
1514    }
arg_types = {'this': False, 'table': False, 'using': False, 'where': False, 'columns': False, 'unique': False, 'primary': False, 'amp': False, 'partition_by': False}
key = 'index'
class Insert(Expression):
1517class Insert(Expression):
1518    arg_types = {
1519        "with": False,
1520        "this": True,
1521        "expression": False,
1522        "conflict": False,
1523        "returning": False,
1524        "overwrite": False,
1525        "exists": False,
1526        "partition": False,
1527        "alternative": False,
1528        "where": False,
1529    }
1530
1531    def with_(
1532        self,
1533        alias: ExpOrStr,
1534        as_: ExpOrStr,
1535        recursive: t.Optional[bool] = None,
1536        append: bool = True,
1537        dialect: DialectType = None,
1538        copy: bool = True,
1539        **opts,
1540    ) -> Insert:
1541        """
1542        Append to or set the common table expressions.
1543
1544        Example:
1545            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1546            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1547
1548        Args:
1549            alias: the SQL code string to parse as the table name.
1550                If an `Expression` instance is passed, this is used as-is.
1551            as_: the SQL code string to parse as the table expression.
1552                If an `Expression` instance is passed, it will be used as-is.
1553            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1554            append: if `True`, add to any existing expressions.
1555                Otherwise, this resets the expressions.
1556            dialect: the dialect used to parse the input expression.
1557            copy: if `False`, modify this expression instance in-place.
1558            opts: other options to use to parse the input expressions.
1559
1560        Returns:
1561            The modified expression.
1562        """
1563        return _apply_cte_builder(
1564            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1565        )
arg_types = {'with': False, 'this': True, 'expression': False, 'conflict': False, 'returning': False, 'overwrite': False, 'exists': False, 'partition': False, 'alternative': False, 'where': False}
def with_( self, alias: Union[str, sqlglot.expressions.Expression], as_: Union[str, sqlglot.expressions.Expression], recursive: Optional[bool] = None, append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Insert:
1531    def with_(
1532        self,
1533        alias: ExpOrStr,
1534        as_: ExpOrStr,
1535        recursive: t.Optional[bool] = None,
1536        append: bool = True,
1537        dialect: DialectType = None,
1538        copy: bool = True,
1539        **opts,
1540    ) -> Insert:
1541        """
1542        Append to or set the common table expressions.
1543
1544        Example:
1545            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1546            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1547
1548        Args:
1549            alias: the SQL code string to parse as the table name.
1550                If an `Expression` instance is passed, this is used as-is.
1551            as_: the SQL code string to parse as the table expression.
1552                If an `Expression` instance is passed, it will be used as-is.
1553            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1554            append: if `True`, add to any existing expressions.
1555                Otherwise, this resets the expressions.
1556            dialect: the dialect used to parse the input expression.
1557            copy: if `False`, modify this expression instance in-place.
1558            opts: other options to use to parse the input expressions.
1559
1560        Returns:
1561            The modified expression.
1562        """
1563        return _apply_cte_builder(
1564            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1565        )

Append to or set the common table expressions.

Example:
>>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
Arguments:
  • alias: the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_: the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive: set the RECURSIVE part of the expression. Defaults to False.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified expression.

key = 'insert'
class OnConflict(Expression):
1568class OnConflict(Expression):
1569    arg_types = {
1570        "duplicate": False,
1571        "expressions": False,
1572        "nothing": False,
1573        "key": False,
1574        "constraint": False,
1575    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1578class Returning(Expression):
1579    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'returning'
class Introducer(Expression):
1583class Introducer(Expression):
1584    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1588class National(Expression):
1589    pass
key = 'national'
class LoadData(Expression):
1592class LoadData(Expression):
1593    arg_types = {
1594        "this": True,
1595        "local": False,
1596        "overwrite": False,
1597        "inpath": True,
1598        "partition": False,
1599        "input_format": False,
1600        "serde": False,
1601    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1604class Partition(Expression):
1605    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1608class Fetch(Expression):
1609    arg_types = {
1610        "direction": False,
1611        "count": False,
1612        "percent": False,
1613        "with_ties": False,
1614    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1617class Group(Expression):
1618    arg_types = {
1619        "expressions": False,
1620        "grouping_sets": False,
1621        "cube": False,
1622        "rollup": False,
1623        "totals": False,
1624    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False}
key = 'group'
class Lambda(Expression):
1627class Lambda(Expression):
1628    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1631class Limit(Expression):
1632    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1635class Literal(Condition):
1636    arg_types = {"this": True, "is_string": True}
1637
1638    @property
1639    def hashable_args(self) -> t.Any:
1640        return (self.this, self.args.get("is_string"))
1641
1642    @classmethod
1643    def number(cls, number) -> Literal:
1644        return cls(this=str(number), is_string=False)
1645
1646    @classmethod
1647    def string(cls, string) -> Literal:
1648        return cls(this=str(string), is_string=True)
1649
1650    @property
1651    def output_name(self) -> str:
1652        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1642    @classmethod
1643    def number(cls, number) -> Literal:
1644        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1646    @classmethod
1647    def string(cls, string) -> Literal:
1648        return cls(this=str(string), is_string=True)
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'literal'
class Join(Expression):
1655class Join(Expression):
1656    arg_types = {
1657        "this": True,
1658        "on": False,
1659        "side": False,
1660        "kind": False,
1661        "using": False,
1662        "method": False,
1663        "global": False,
1664        "hint": False,
1665    }
1666
1667    @property
1668    def method(self) -> str:
1669        return self.text("method").upper()
1670
1671    @property
1672    def kind(self) -> str:
1673        return self.text("kind").upper()
1674
1675    @property
1676    def side(self) -> str:
1677        return self.text("side").upper()
1678
1679    @property
1680    def hint(self) -> str:
1681        return self.text("hint").upper()
1682
1683    @property
1684    def alias_or_name(self) -> str:
1685        return self.this.alias_or_name
1686
1687    def on(
1688        self,
1689        *expressions: t.Optional[ExpOrStr],
1690        append: bool = True,
1691        dialect: DialectType = None,
1692        copy: bool = True,
1693        **opts,
1694    ) -> Join:
1695        """
1696        Append to or set the ON expressions.
1697
1698        Example:
1699            >>> import sqlglot
1700            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1701            'JOIN x ON y = 1'
1702
1703        Args:
1704            *expressions: the SQL code strings to parse.
1705                If an `Expression` instance is passed, it will be used as-is.
1706                Multiple expressions are combined with an AND operator.
1707            append: if `True`, AND the new expressions to any existing expression.
1708                Otherwise, this resets the expression.
1709            dialect: the dialect used to parse the input expressions.
1710            copy: if `False`, modify this expression instance in-place.
1711            opts: other options to use to parse the input expressions.
1712
1713        Returns:
1714            The modified Join expression.
1715        """
1716        join = _apply_conjunction_builder(
1717            *expressions,
1718            instance=self,
1719            arg="on",
1720            append=append,
1721            dialect=dialect,
1722            copy=copy,
1723            **opts,
1724        )
1725
1726        if join.kind == "CROSS":
1727            join.set("kind", None)
1728
1729        return join
1730
1731    def using(
1732        self,
1733        *expressions: t.Optional[ExpOrStr],
1734        append: bool = True,
1735        dialect: DialectType = None,
1736        copy: bool = True,
1737        **opts,
1738    ) -> Join:
1739        """
1740        Append to or set the USING expressions.
1741
1742        Example:
1743            >>> import sqlglot
1744            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1745            'JOIN x USING (foo, bla)'
1746
1747        Args:
1748            *expressions: the SQL code strings to parse.
1749                If an `Expression` instance is passed, it will be used as-is.
1750            append: if `True`, concatenate the new expressions to the existing "using" list.
1751                Otherwise, this resets the expression.
1752            dialect: the dialect used to parse the input expressions.
1753            copy: if `False`, modify this expression instance in-place.
1754            opts: other options to use to parse the input expressions.
1755
1756        Returns:
1757            The modified Join expression.
1758        """
1759        join = _apply_list_builder(
1760            *expressions,
1761            instance=self,
1762            arg="using",
1763            append=append,
1764            dialect=dialect,
1765            copy=copy,
1766            **opts,
1767        )
1768
1769        if join.kind == "CROSS":
1770            join.set("kind", None)
1771
1772        return join
arg_types = {'this': True, 'on': False, 'side': False, 'kind': False, 'using': False, 'method': False, 'global': False, 'hint': False}
method: str
kind: str
side: str
hint: str
alias_or_name: str
def on( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Join:
1687    def on(
1688        self,
1689        *expressions: t.Optional[ExpOrStr],
1690        append: bool = True,
1691        dialect: DialectType = None,
1692        copy: bool = True,
1693        **opts,
1694    ) -> Join:
1695        """
1696        Append to or set the ON expressions.
1697
1698        Example:
1699            >>> import sqlglot
1700            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1701            'JOIN x ON y = 1'
1702
1703        Args:
1704            *expressions: the SQL code strings to parse.
1705                If an `Expression` instance is passed, it will be used as-is.
1706                Multiple expressions are combined with an AND operator.
1707            append: if `True`, AND the new expressions to any existing expression.
1708                Otherwise, this resets the expression.
1709            dialect: the dialect used to parse the input expressions.
1710            copy: if `False`, modify this expression instance in-place.
1711            opts: other options to use to parse the input expressions.
1712
1713        Returns:
1714            The modified Join expression.
1715        """
1716        join = _apply_conjunction_builder(
1717            *expressions,
1718            instance=self,
1719            arg="on",
1720            append=append,
1721            dialect=dialect,
1722            copy=copy,
1723            **opts,
1724        )
1725
1726        if join.kind == "CROSS":
1727            join.set("kind", None)
1728
1729        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

def using( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Join:
1731    def using(
1732        self,
1733        *expressions: t.Optional[ExpOrStr],
1734        append: bool = True,
1735        dialect: DialectType = None,
1736        copy: bool = True,
1737        **opts,
1738    ) -> Join:
1739        """
1740        Append to or set the USING expressions.
1741
1742        Example:
1743            >>> import sqlglot
1744            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1745            'JOIN x USING (foo, bla)'
1746
1747        Args:
1748            *expressions: the SQL code strings to parse.
1749                If an `Expression` instance is passed, it will be used as-is.
1750            append: if `True`, concatenate the new expressions to the existing "using" list.
1751                Otherwise, this resets the expression.
1752            dialect: the dialect used to parse the input expressions.
1753            copy: if `False`, modify this expression instance in-place.
1754            opts: other options to use to parse the input expressions.
1755
1756        Returns:
1757            The modified Join expression.
1758        """
1759        join = _apply_list_builder(
1760            *expressions,
1761            instance=self,
1762            arg="using",
1763            append=append,
1764            dialect=dialect,
1765            copy=copy,
1766            **opts,
1767        )
1768
1769        if join.kind == "CROSS":
1770            join.set("kind", None)
1771
1772        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

key = 'join'
class Lateral(UDTF):
1775class Lateral(UDTF):
1776    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
arg_types = {'this': True, 'view': False, 'outer': False, 'alias': False}
key = 'lateral'
class MatchRecognize(Expression):
1779class MatchRecognize(Expression):
1780    arg_types = {
1781        "partition_by": False,
1782        "order": False,
1783        "measures": False,
1784        "rows": False,
1785        "after": False,
1786        "pattern": False,
1787        "define": False,
1788        "alias": False,
1789    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1794class Final(Expression):
1795    pass
key = 'final'
class Offset(Expression):
1798class Offset(Expression):
1799    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1802class Order(Expression):
1803    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1808class Cluster(Order):
1809    pass
key = 'cluster'
class Distribute(Order):
1812class Distribute(Order):
1813    pass
key = 'distribute'
class Sort(Order):
1816class Sort(Order):
1817    pass
key = 'sort'
class Ordered(Expression):
1820class Ordered(Expression):
1821    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1824class Property(Expression):
1825    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1828class AlgorithmProperty(Property):
1829    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1832class AutoIncrementProperty(Property):
1833    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1836class BlockCompressionProperty(Property):
1837    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
arg_types = {'autotemp': False, 'always': False, 'default': True, 'manual': True, 'never': True}
key = 'blockcompressionproperty'
class CharacterSetProperty(Property):
1840class CharacterSetProperty(Property):
1841    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1844class ChecksumProperty(Property):
1845    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1848class CollateProperty(Property):
1849    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1852class CopyGrantsProperty(Property):
1853    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1856class DataBlocksizeProperty(Property):
1857    arg_types = {
1858        "size": False,
1859        "units": False,
1860        "minimum": False,
1861        "maximum": False,
1862        "default": False,
1863    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1866class DefinerProperty(Property):
1867    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1870class DistKeyProperty(Property):
1871    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1874class DistStyleProperty(Property):
1875    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1878class EngineProperty(Property):
1879    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class ToTableProperty(Property):
1882class ToTableProperty(Property):
1883    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1886class ExecuteAsProperty(Property):
1887    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1890class ExternalProperty(Property):
1891    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1894class FallbackProperty(Property):
1895    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1898class FileFormatProperty(Property):
1899    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1902class FreespaceProperty(Property):
1903    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1906class InputOutputFormat(Expression):
1907    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1910class IsolatedLoadingProperty(Property):
1911    arg_types = {
1912        "no": True,
1913        "concurrent": True,
1914        "for_all": True,
1915        "for_insert": True,
1916        "for_none": True,
1917    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1920class JournalProperty(Property):
1921    arg_types = {
1922        "no": False,
1923        "dual": False,
1924        "before": False,
1925        "local": False,
1926        "after": False,
1927    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1930class LanguageProperty(Property):
1931    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
1935class ClusteredByProperty(Property):
1936    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
1939class DictProperty(Property):
1940    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
1943class DictSubProperty(Property):
1944    pass
key = 'dictsubproperty'
class DictRange(Property):
1947class DictRange(Property):
1948    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
1953class OnCluster(Property):
1954    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
1957class LikeProperty(Property):
1958    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
1961class LocationProperty(Property):
1962    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
1965class LockingProperty(Property):
1966    arg_types = {
1967        "this": False,
1968        "kind": True,
1969        "for_or_in": True,
1970        "lock_type": True,
1971        "override": False,
1972    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
1975class LogProperty(Property):
1976    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
1979class MaterializedProperty(Property):
1980    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
1983class MergeBlockRatioProperty(Property):
1984    arg_types = {"this": False, "no": False, "default": False, "percent": False}
arg_types = {'this': False, 'no': False, 'default': False, 'percent': False}
key = 'mergeblockratioproperty'
class NoPrimaryIndexProperty(Property):
1987class NoPrimaryIndexProperty(Property):
1988    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
1991class OnCommitProperty(Property):
1992    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
1995class PartitionedByProperty(Property):
1996    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
1999class ReturnsProperty(Property):
2000    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2003class RowFormatProperty(Property):
2004    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2007class RowFormatDelimitedProperty(Property):
2008    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2009    arg_types = {
2010        "fields": False,
2011        "escaped": False,
2012        "collection_items": False,
2013        "map_keys": False,
2014        "lines": False,
2015        "null": False,
2016        "serde": False,
2017    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2020class RowFormatSerdeProperty(Property):
2021    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatserdeproperty'
class SchemaCommentProperty(Property):
2024class SchemaCommentProperty(Property):
2025    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2028class SerdeProperties(Property):
2029    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2032class SetProperty(Property):
2033    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2036class SettingsProperty(Property):
2037    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2040class SortKeyProperty(Property):
2041    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2044class SqlSecurityProperty(Property):
2045    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2048class StabilityProperty(Property):
2049    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2052class TemporaryProperty(Property):
2053    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2056class TransientProperty(Property):
2057    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2060class VolatileProperty(Property):
2061    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2064class WithDataProperty(Property):
2065    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2068class WithJournalTableProperty(Property):
2069    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2072class Properties(Expression):
2073    arg_types = {"expressions": True}
2074
2075    NAME_TO_PROPERTY = {
2076        "ALGORITHM": AlgorithmProperty,
2077        "AUTO_INCREMENT": AutoIncrementProperty,
2078        "CHARACTER SET": CharacterSetProperty,
2079        "CLUSTERED_BY": ClusteredByProperty,
2080        "COLLATE": CollateProperty,
2081        "COMMENT": SchemaCommentProperty,
2082        "DEFINER": DefinerProperty,
2083        "DISTKEY": DistKeyProperty,
2084        "DISTSTYLE": DistStyleProperty,
2085        "ENGINE": EngineProperty,
2086        "EXECUTE AS": ExecuteAsProperty,
2087        "FORMAT": FileFormatProperty,
2088        "LANGUAGE": LanguageProperty,
2089        "LOCATION": LocationProperty,
2090        "PARTITIONED_BY": PartitionedByProperty,
2091        "RETURNS": ReturnsProperty,
2092        "ROW_FORMAT": RowFormatProperty,
2093        "SORTKEY": SortKeyProperty,
2094    }
2095
2096    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2097
2098    # CREATE property locations
2099    # Form: schema specified
2100    #   create [POST_CREATE]
2101    #     table a [POST_NAME]
2102    #     (b int) [POST_SCHEMA]
2103    #     with ([POST_WITH])
2104    #     index (b) [POST_INDEX]
2105    #
2106    # Form: alias selection
2107    #   create [POST_CREATE]
2108    #     table a [POST_NAME]
2109    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2110    #     index (c) [POST_INDEX]
2111    class Location(AutoName):
2112        POST_CREATE = auto()
2113        POST_NAME = auto()
2114        POST_SCHEMA = auto()
2115        POST_WITH = auto()
2116        POST_ALIAS = auto()
2117        POST_EXPRESSION = auto()
2118        POST_INDEX = auto()
2119        UNSUPPORTED = auto()
2120
2121    @classmethod
2122    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2123        expressions = []
2124        for key, value in properties_dict.items():
2125            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2126            if property_cls:
2127                expressions.append(property_cls(this=convert(value)))
2128            else:
2129                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2130
2131        return cls(expressions=expressions)
arg_types = {'expressions': True}
NAME_TO_PROPERTY = {'ALGORITHM': <class 'sqlglot.expressions.AlgorithmProperty'>, 'AUTO_INCREMENT': <class 'sqlglot.expressions.AutoIncrementProperty'>, 'CHARACTER SET': <class 'sqlglot.expressions.CharacterSetProperty'>, 'CLUSTERED_BY': <class 'sqlglot.expressions.ClusteredByProperty'>, 'COLLATE': <class 'sqlglot.expressions.CollateProperty'>, 'COMMENT': <class 'sqlglot.expressions.SchemaCommentProperty'>, 'DEFINER': <class 'sqlglot.expressions.DefinerProperty'>, 'DISTKEY': <class 'sqlglot.expressions.DistKeyProperty'>, 'DISTSTYLE': <class 'sqlglot.expressions.DistStyleProperty'>, 'ENGINE': <class 'sqlglot.expressions.EngineProperty'>, 'EXECUTE AS': <class 'sqlglot.expressions.ExecuteAsProperty'>, 'FORMAT': <class 'sqlglot.expressions.FileFormatProperty'>, 'LANGUAGE': <class 'sqlglot.expressions.LanguageProperty'>, 'LOCATION': <class 'sqlglot.expressions.LocationProperty'>, 'PARTITIONED_BY': <class 'sqlglot.expressions.PartitionedByProperty'>, 'RETURNS': <class 'sqlglot.expressions.ReturnsProperty'>, 'ROW_FORMAT': <class 'sqlglot.expressions.RowFormatProperty'>, 'SORTKEY': <class 'sqlglot.expressions.SortKeyProperty'>}
PROPERTY_TO_NAME = {<class 'sqlglot.expressions.AlgorithmProperty'>: 'ALGORITHM', <class 'sqlglot.expressions.AutoIncrementProperty'>: 'AUTO_INCREMENT', <class 'sqlglot.expressions.CharacterSetProperty'>: 'CHARACTER SET', <class 'sqlglot.expressions.ClusteredByProperty'>: 'CLUSTERED_BY', <class 'sqlglot.expressions.CollateProperty'>: 'COLLATE', <class 'sqlglot.expressions.SchemaCommentProperty'>: 'COMMENT', <class 'sqlglot.expressions.DefinerProperty'>: 'DEFINER', <class 'sqlglot.expressions.DistKeyProperty'>: 'DISTKEY', <class 'sqlglot.expressions.DistStyleProperty'>: 'DISTSTYLE', <class 'sqlglot.expressions.EngineProperty'>: 'ENGINE', <class 'sqlglot.expressions.ExecuteAsProperty'>: 'EXECUTE AS', <class 'sqlglot.expressions.FileFormatProperty'>: 'FORMAT', <class 'sqlglot.expressions.LanguageProperty'>: 'LANGUAGE', <class 'sqlglot.expressions.LocationProperty'>: 'LOCATION', <class 'sqlglot.expressions.PartitionedByProperty'>: 'PARTITIONED_BY', <class 'sqlglot.expressions.ReturnsProperty'>: 'RETURNS', <class 'sqlglot.expressions.RowFormatProperty'>: 'ROW_FORMAT', <class 'sqlglot.expressions.SortKeyProperty'>: 'SORTKEY'}
@classmethod
def from_dict(cls, properties_dict: Dict) -> sqlglot.expressions.Properties:
2121    @classmethod
2122    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2123        expressions = []
2124        for key, value in properties_dict.items():
2125            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2126            if property_cls:
2127                expressions.append(property_cls(this=convert(value)))
2128            else:
2129                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2130
2131        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2111    class Location(AutoName):
2112        POST_CREATE = auto()
2113        POST_NAME = auto()
2114        POST_SCHEMA = auto()
2115        POST_WITH = auto()
2116        POST_ALIAS = auto()
2117        POST_EXPRESSION = auto()
2118        POST_INDEX = auto()
2119        UNSUPPORTED = auto()

An enumeration.

POST_CREATE = <Location.POST_CREATE: 'POST_CREATE'>
POST_NAME = <Location.POST_NAME: 'POST_NAME'>
POST_SCHEMA = <Location.POST_SCHEMA: 'POST_SCHEMA'>
POST_WITH = <Location.POST_WITH: 'POST_WITH'>
POST_ALIAS = <Location.POST_ALIAS: 'POST_ALIAS'>
POST_EXPRESSION = <Location.POST_EXPRESSION: 'POST_EXPRESSION'>
POST_INDEX = <Location.POST_INDEX: 'POST_INDEX'>
UNSUPPORTED = <Location.UNSUPPORTED: 'UNSUPPORTED'>
Inherited Members
enum.Enum
name
value
class Qualify(Expression):
2134class Qualify(Expression):
2135    pass
key = 'qualify'
class Return(Expression):
2139class Return(Expression):
2140    pass
key = 'return'
class Reference(Expression):
2143class Reference(Expression):
2144    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2147class Tuple(Expression):
2148    arg_types = {"expressions": False}
2149
2150    def isin(
2151        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2152    ) -> In:
2153        return In(
2154            this=_maybe_copy(self, copy),
2155            expressions=[convert(e, copy=copy) for e in expressions],
2156            query=maybe_parse(query, copy=copy, **opts) if query else None,
2157        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
2150    def isin(
2151        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2152    ) -> In:
2153        return In(
2154            this=_maybe_copy(self, copy),
2155            expressions=[convert(e, copy=copy) for e in expressions],
2156            query=maybe_parse(query, copy=copy, **opts) if query else None,
2157        )
key = 'tuple'
class Subqueryable(Unionable):
2160class Subqueryable(Unionable):
2161    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2162        """
2163        Convert this expression to an aliased expression that can be used as a Subquery.
2164
2165        Example:
2166            >>> subquery = Select().select("x").from_("tbl").subquery()
2167            >>> Select().select("x").from_(subquery).sql()
2168            'SELECT x FROM (SELECT x FROM tbl)'
2169
2170        Args:
2171            alias (str | Identifier): an optional alias for the subquery
2172            copy (bool): if `False`, modify this expression instance in-place.
2173
2174        Returns:
2175            Alias: the subquery
2176        """
2177        instance = _maybe_copy(self, copy)
2178        if not isinstance(alias, Expression):
2179            alias = TableAlias(this=to_identifier(alias)) if alias else None
2180
2181        return Subquery(this=instance, alias=alias)
2182
2183    def limit(
2184        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2185    ) -> Select:
2186        raise NotImplementedError
2187
2188    @property
2189    def ctes(self):
2190        with_ = self.args.get("with")
2191        if not with_:
2192            return []
2193        return with_.expressions
2194
2195    @property
2196    def selects(self):
2197        raise NotImplementedError("Subqueryable objects must implement `selects`")
2198
2199    @property
2200    def named_selects(self):
2201        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2202
2203    def with_(
2204        self,
2205        alias: ExpOrStr,
2206        as_: ExpOrStr,
2207        recursive: t.Optional[bool] = None,
2208        append: bool = True,
2209        dialect: DialectType = None,
2210        copy: bool = True,
2211        **opts,
2212    ) -> Subqueryable:
2213        """
2214        Append to or set the common table expressions.
2215
2216        Example:
2217            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2218            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2219
2220        Args:
2221            alias: the SQL code string to parse as the table name.
2222                If an `Expression` instance is passed, this is used as-is.
2223            as_: the SQL code string to parse as the table expression.
2224                If an `Expression` instance is passed, it will be used as-is.
2225            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2226            append: if `True`, add to any existing expressions.
2227                Otherwise, this resets the expressions.
2228            dialect: the dialect used to parse the input expression.
2229            copy: if `False`, modify this expression instance in-place.
2230            opts: other options to use to parse the input expressions.
2231
2232        Returns:
2233            The modified expression.
2234        """
2235        return _apply_cte_builder(
2236            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2237        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2161    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2162        """
2163        Convert this expression to an aliased expression that can be used as a Subquery.
2164
2165        Example:
2166            >>> subquery = Select().select("x").from_("tbl").subquery()
2167            >>> Select().select("x").from_(subquery).sql()
2168            'SELECT x FROM (SELECT x FROM tbl)'
2169
2170        Args:
2171            alias (str | Identifier): an optional alias for the subquery
2172            copy (bool): if `False`, modify this expression instance in-place.
2173
2174        Returns:
2175            Alias: the subquery
2176        """
2177        instance = _maybe_copy(self, copy)
2178        if not isinstance(alias, Expression):
2179            alias = TableAlias(this=to_identifier(alias)) if alias else None
2180
2181        return Subquery(this=instance, alias=alias)

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2183    def limit(
2184        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2185    ) -> Select:
2186        raise NotImplementedError
ctes
selects
named_selects
def with_( self, alias: Union[str, sqlglot.expressions.Expression], as_: Union[str, sqlglot.expressions.Expression], recursive: Optional[bool] = None, append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Subqueryable:
2203    def with_(
2204        self,
2205        alias: ExpOrStr,
2206        as_: ExpOrStr,
2207        recursive: t.Optional[bool] = None,
2208        append: bool = True,
2209        dialect: DialectType = None,
2210        copy: bool = True,
2211        **opts,
2212    ) -> Subqueryable:
2213        """
2214        Append to or set the common table expressions.
2215
2216        Example:
2217            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2218            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2219
2220        Args:
2221            alias: the SQL code string to parse as the table name.
2222                If an `Expression` instance is passed, this is used as-is.
2223            as_: the SQL code string to parse as the table expression.
2224                If an `Expression` instance is passed, it will be used as-is.
2225            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2226            append: if `True`, add to any existing expressions.
2227                Otherwise, this resets the expressions.
2228            dialect: the dialect used to parse the input expression.
2229            copy: if `False`, modify this expression instance in-place.
2230            opts: other options to use to parse the input expressions.
2231
2232        Returns:
2233            The modified expression.
2234        """
2235        return _apply_cte_builder(
2236            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2237        )

Append to or set the common table expressions.

Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
  • alias: the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_: the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive: set the RECURSIVE part of the expression. Defaults to False.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified expression.

key = 'subqueryable'
QUERY_MODIFIERS = {'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
class WithTableHint(Expression):
2264class WithTableHint(Expression):
2265    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2269class IndexTableHint(Expression):
2270    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2273class Table(Expression):
2274    arg_types = {
2275        "this": True,
2276        "alias": False,
2277        "db": False,
2278        "catalog": False,
2279        "laterals": False,
2280        "joins": False,
2281        "pivots": False,
2282        "hints": False,
2283        "system_time": False,
2284    }
2285
2286    @property
2287    def db(self) -> str:
2288        return self.text("db")
2289
2290    @property
2291    def catalog(self) -> str:
2292        return self.text("catalog")
2293
2294    @property
2295    def parts(self) -> t.List[Identifier]:
2296        """Return the parts of a table in order catalog, db, table."""
2297        return [
2298            t.cast(Identifier, self.args[part])
2299            for part in ("catalog", "db", "this")
2300            if self.args.get(part)
2301        ]
arg_types = {'this': True, 'alias': False, 'db': False, 'catalog': False, 'laterals': False, 'joins': False, 'pivots': False, 'hints': False, 'system_time': False}
db: str
catalog: str

Return the parts of a table in order catalog, db, table.

key = 'table'
class SystemTime(Expression):
2305class SystemTime(Expression):
2306    arg_types = {
2307        "this": False,
2308        "expression": False,
2309        "kind": True,
2310    }
arg_types = {'this': False, 'expression': False, 'kind': True}
key = 'systemtime'
class Union(Subqueryable):
2313class Union(Subqueryable):
2314    arg_types = {
2315        "with": False,
2316        "this": True,
2317        "expression": True,
2318        "distinct": False,
2319        **QUERY_MODIFIERS,
2320    }
2321
2322    def limit(
2323        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2324    ) -> Select:
2325        """
2326        Set the LIMIT expression.
2327
2328        Example:
2329            >>> select("1").union(select("1")).limit(1).sql()
2330            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2331
2332        Args:
2333            expression: the SQL code string to parse.
2334                This can also be an integer.
2335                If a `Limit` instance is passed, this is used as-is.
2336                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2337            dialect: the dialect used to parse the input expression.
2338            copy: if `False`, modify this expression instance in-place.
2339            opts: other options to use to parse the input expressions.
2340
2341        Returns:
2342            The limited subqueryable.
2343        """
2344        return (
2345            select("*")
2346            .from_(self.subquery(alias="_l_0", copy=copy))
2347            .limit(expression, dialect=dialect, copy=False, **opts)
2348        )
2349
2350    def select(
2351        self,
2352        *expressions: t.Optional[ExpOrStr],
2353        append: bool = True,
2354        dialect: DialectType = None,
2355        copy: bool = True,
2356        **opts,
2357    ) -> Union:
2358        """Append to or set the SELECT of the union recursively.
2359
2360        Example:
2361            >>> from sqlglot import parse_one
2362            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2363            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2364
2365        Args:
2366            *expressions: the SQL code strings to parse.
2367                If an `Expression` instance is passed, it will be used as-is.
2368            append: if `True`, add to any existing expressions.
2369                Otherwise, this resets the expressions.
2370            dialect: the dialect used to parse the input expressions.
2371            copy: if `False`, modify this expression instance in-place.
2372            opts: other options to use to parse the input expressions.
2373
2374        Returns:
2375            Union: the modified expression.
2376        """
2377        this = self.copy() if copy else self
2378        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2379        this.expression.unnest().select(
2380            *expressions, append=append, dialect=dialect, copy=False, **opts
2381        )
2382        return this
2383
2384    @property
2385    def named_selects(self):
2386        return self.this.unnest().named_selects
2387
2388    @property
2389    def is_star(self) -> bool:
2390        return self.this.is_star or self.expression.is_star
2391
2392    @property
2393    def selects(self):
2394        return self.this.unnest().selects
2395
2396    @property
2397    def left(self):
2398        return self.this
2399
2400    @property
2401    def right(self):
2402        return self.expression
arg_types = {'with': False, 'this': True, 'expression': True, 'distinct': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2322    def limit(
2323        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2324    ) -> Select:
2325        """
2326        Set the LIMIT expression.
2327
2328        Example:
2329            >>> select("1").union(select("1")).limit(1).sql()
2330            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2331
2332        Args:
2333            expression: the SQL code string to parse.
2334                This can also be an integer.
2335                If a `Limit` instance is passed, this is used as-is.
2336                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2337            dialect: the dialect used to parse the input expression.
2338            copy: if `False`, modify this expression instance in-place.
2339            opts: other options to use to parse the input expressions.
2340
2341        Returns:
2342            The limited subqueryable.
2343        """
2344        return (
2345            select("*")
2346            .from_(self.subquery(alias="_l_0", copy=copy))
2347            .limit(expression, dialect=dialect, copy=False, **opts)
2348        )

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The limited subqueryable.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Union:
2350    def select(
2351        self,
2352        *expressions: t.Optional[ExpOrStr],
2353        append: bool = True,
2354        dialect: DialectType = None,
2355        copy: bool = True,
2356        **opts,
2357    ) -> Union:
2358        """Append to or set the SELECT of the union recursively.
2359
2360        Example:
2361            >>> from sqlglot import parse_one
2362            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2363            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2364
2365        Args:
2366            *expressions: the SQL code strings to parse.
2367                If an `Expression` instance is passed, it will be used as-is.
2368            append: if `True`, add to any existing expressions.
2369                Otherwise, this resets the expressions.
2370            dialect: the dialect used to parse the input expressions.
2371            copy: if `False`, modify this expression instance in-place.
2372            opts: other options to use to parse the input expressions.
2373
2374        Returns:
2375            Union: the modified expression.
2376        """
2377        this = self.copy() if copy else self
2378        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2379        this.expression.unnest().select(
2380            *expressions, append=append, dialect=dialect, copy=False, **opts
2381        )
2382        return this

Append to or set the SELECT of the union recursively.

Example:
>>> from sqlglot import parse_one
>>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Union: the modified expression.

named_selects
is_star: bool

Checks whether an expression is a star.

selects
left
right
key = 'union'
class Except(Union):
2405class Except(Union):
2406    pass
key = 'except'
class Intersect(Union):
2409class Intersect(Union):
2410    pass
key = 'intersect'
class Unnest(UDTF):
2413class Unnest(UDTF):
2414    arg_types = {
2415        "expressions": True,
2416        "ordinality": False,
2417        "alias": False,
2418        "offset": False,
2419    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False, 'offset': False}
key = 'unnest'
class Update(Expression):
2422class Update(Expression):
2423    arg_types = {
2424        "with": False,
2425        "this": False,
2426        "expressions": True,
2427        "from": False,
2428        "where": False,
2429        "returning": False,
2430        "limit": False,
2431    }
arg_types = {'with': False, 'this': False, 'expressions': True, 'from': False, 'where': False, 'returning': False, 'limit': False}
key = 'update'
class Values(UDTF):
2434class Values(UDTF):
2435    arg_types = {
2436        "expressions": True,
2437        "ordinality": False,
2438        "alias": False,
2439    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False}
key = 'values'
class Var(Expression):
2442class Var(Expression):
2443    pass
key = 'var'
class Schema(Expression):
2446class Schema(Expression):
2447    arg_types = {"this": False, "expressions": False}
arg_types = {'this': False, 'expressions': False}
key = 'schema'
class Lock(Expression):
2452class Lock(Expression):
2453    arg_types = {"update": True, "expressions": False, "wait": False}
arg_types = {'update': True, 'expressions': False, 'wait': False}
key = 'lock'
class Select(Subqueryable):
2456class Select(Subqueryable):
2457    arg_types = {
2458        "with": False,
2459        "kind": False,
2460        "expressions": False,
2461        "hint": False,
2462        "distinct": False,
2463        "into": False,
2464        "from": False,
2465        **QUERY_MODIFIERS,
2466    }
2467
2468    def from_(
2469        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2470    ) -> Select:
2471        """
2472        Set the FROM expression.
2473
2474        Example:
2475            >>> Select().from_("tbl").select("x").sql()
2476            'SELECT x FROM tbl'
2477
2478        Args:
2479            expression : the SQL code strings to parse.
2480                If a `From` instance is passed, this is used as-is.
2481                If another `Expression` instance is passed, it will be wrapped in a `From`.
2482            dialect: the dialect used to parse the input expression.
2483            copy: if `False`, modify this expression instance in-place.
2484            opts: other options to use to parse the input expressions.
2485
2486        Returns:
2487            The modified Select expression.
2488        """
2489        return _apply_builder(
2490            expression=expression,
2491            instance=self,
2492            arg="from",
2493            into=From,
2494            prefix="FROM",
2495            dialect=dialect,
2496            copy=copy,
2497            **opts,
2498        )
2499
2500    def group_by(
2501        self,
2502        *expressions: t.Optional[ExpOrStr],
2503        append: bool = True,
2504        dialect: DialectType = None,
2505        copy: bool = True,
2506        **opts,
2507    ) -> Select:
2508        """
2509        Set the GROUP BY expression.
2510
2511        Example:
2512            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2513            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2514
2515        Args:
2516            *expressions: the SQL code strings to parse.
2517                If a `Group` instance is passed, this is used as-is.
2518                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2519                If nothing is passed in then a group by is not applied to the expression
2520            append: if `True`, add to any existing expressions.
2521                Otherwise, this flattens all the `Group` expression into a single expression.
2522            dialect: the dialect used to parse the input expression.
2523            copy: if `False`, modify this expression instance in-place.
2524            opts: other options to use to parse the input expressions.
2525
2526        Returns:
2527            The modified Select expression.
2528        """
2529        if not expressions:
2530            return self if not copy else self.copy()
2531
2532        return _apply_child_list_builder(
2533            *expressions,
2534            instance=self,
2535            arg="group",
2536            append=append,
2537            copy=copy,
2538            prefix="GROUP BY",
2539            into=Group,
2540            dialect=dialect,
2541            **opts,
2542        )
2543
2544    def order_by(
2545        self,
2546        *expressions: t.Optional[ExpOrStr],
2547        append: bool = True,
2548        dialect: DialectType = None,
2549        copy: bool = True,
2550        **opts,
2551    ) -> Select:
2552        """
2553        Set the ORDER BY expression.
2554
2555        Example:
2556            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2557            'SELECT x FROM tbl ORDER BY x DESC'
2558
2559        Args:
2560            *expressions: the SQL code strings to parse.
2561                If a `Group` instance is passed, this is used as-is.
2562                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2563            append: if `True`, add to any existing expressions.
2564                Otherwise, this flattens all the `Order` expression into a single expression.
2565            dialect: the dialect used to parse the input expression.
2566            copy: if `False`, modify this expression instance in-place.
2567            opts: other options to use to parse the input expressions.
2568
2569        Returns:
2570            The modified Select expression.
2571        """
2572        return _apply_child_list_builder(
2573            *expressions,
2574            instance=self,
2575            arg="order",
2576            append=append,
2577            copy=copy,
2578            prefix="ORDER BY",
2579            into=Order,
2580            dialect=dialect,
2581            **opts,
2582        )
2583
2584    def sort_by(
2585        self,
2586        *expressions: t.Optional[ExpOrStr],
2587        append: bool = True,
2588        dialect: DialectType = None,
2589        copy: bool = True,
2590        **opts,
2591    ) -> Select:
2592        """
2593        Set the SORT BY expression.
2594
2595        Example:
2596            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2597            'SELECT x FROM tbl SORT BY x DESC'
2598
2599        Args:
2600            *expressions: the SQL code strings to parse.
2601                If a `Group` instance is passed, this is used as-is.
2602                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2603            append: if `True`, add to any existing expressions.
2604                Otherwise, this flattens all the `Order` expression into a single expression.
2605            dialect: the dialect used to parse the input expression.
2606            copy: if `False`, modify this expression instance in-place.
2607            opts: other options to use to parse the input expressions.
2608
2609        Returns:
2610            The modified Select expression.
2611        """
2612        return _apply_child_list_builder(
2613            *expressions,
2614            instance=self,
2615            arg="sort",
2616            append=append,
2617            copy=copy,
2618            prefix="SORT BY",
2619            into=Sort,
2620            dialect=dialect,
2621            **opts,
2622        )
2623
2624    def cluster_by(
2625        self,
2626        *expressions: t.Optional[ExpOrStr],
2627        append: bool = True,
2628        dialect: DialectType = None,
2629        copy: bool = True,
2630        **opts,
2631    ) -> Select:
2632        """
2633        Set the CLUSTER BY expression.
2634
2635        Example:
2636            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2637            'SELECT x FROM tbl CLUSTER BY x DESC'
2638
2639        Args:
2640            *expressions: the SQL code strings to parse.
2641                If a `Group` instance is passed, this is used as-is.
2642                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2643            append: if `True`, add to any existing expressions.
2644                Otherwise, this flattens all the `Order` expression into a single expression.
2645            dialect: the dialect used to parse the input expression.
2646            copy: if `False`, modify this expression instance in-place.
2647            opts: other options to use to parse the input expressions.
2648
2649        Returns:
2650            The modified Select expression.
2651        """
2652        return _apply_child_list_builder(
2653            *expressions,
2654            instance=self,
2655            arg="cluster",
2656            append=append,
2657            copy=copy,
2658            prefix="CLUSTER BY",
2659            into=Cluster,
2660            dialect=dialect,
2661            **opts,
2662        )
2663
2664    def limit(
2665        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2666    ) -> Select:
2667        """
2668        Set the LIMIT expression.
2669
2670        Example:
2671            >>> Select().from_("tbl").select("x").limit(10).sql()
2672            'SELECT x FROM tbl LIMIT 10'
2673
2674        Args:
2675            expression: the SQL code string to parse.
2676                This can also be an integer.
2677                If a `Limit` instance is passed, this is used as-is.
2678                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2679            dialect: the dialect used to parse the input expression.
2680            copy: if `False`, modify this expression instance in-place.
2681            opts: other options to use to parse the input expressions.
2682
2683        Returns:
2684            Select: the modified expression.
2685        """
2686        return _apply_builder(
2687            expression=expression,
2688            instance=self,
2689            arg="limit",
2690            into=Limit,
2691            prefix="LIMIT",
2692            dialect=dialect,
2693            copy=copy,
2694            **opts,
2695        )
2696
2697    def offset(
2698        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2699    ) -> Select:
2700        """
2701        Set the OFFSET expression.
2702
2703        Example:
2704            >>> Select().from_("tbl").select("x").offset(10).sql()
2705            'SELECT x FROM tbl OFFSET 10'
2706
2707        Args:
2708            expression: the SQL code string to parse.
2709                This can also be an integer.
2710                If a `Offset` instance is passed, this is used as-is.
2711                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2712            dialect: the dialect used to parse the input expression.
2713            copy: if `False`, modify this expression instance in-place.
2714            opts: other options to use to parse the input expressions.
2715
2716        Returns:
2717            The modified Select expression.
2718        """
2719        return _apply_builder(
2720            expression=expression,
2721            instance=self,
2722            arg="offset",
2723            into=Offset,
2724            prefix="OFFSET",
2725            dialect=dialect,
2726            copy=copy,
2727            **opts,
2728        )
2729
2730    def select(
2731        self,
2732        *expressions: t.Optional[ExpOrStr],
2733        append: bool = True,
2734        dialect: DialectType = None,
2735        copy: bool = True,
2736        **opts,
2737    ) -> Select:
2738        """
2739        Append to or set the SELECT expressions.
2740
2741        Example:
2742            >>> Select().select("x", "y").sql()
2743            'SELECT x, y'
2744
2745        Args:
2746            *expressions: the SQL code strings to parse.
2747                If an `Expression` instance is passed, it will be used as-is.
2748            append: if `True`, add to any existing expressions.
2749                Otherwise, this resets the expressions.
2750            dialect: the dialect used to parse the input expressions.
2751            copy: if `False`, modify this expression instance in-place.
2752            opts: other options to use to parse the input expressions.
2753
2754        Returns:
2755            The modified Select expression.
2756        """
2757        return _apply_list_builder(
2758            *expressions,
2759            instance=self,
2760            arg="expressions",
2761            append=append,
2762            dialect=dialect,
2763            copy=copy,
2764            **opts,
2765        )
2766
2767    def lateral(
2768        self,
2769        *expressions: t.Optional[ExpOrStr],
2770        append: bool = True,
2771        dialect: DialectType = None,
2772        copy: bool = True,
2773        **opts,
2774    ) -> Select:
2775        """
2776        Append to or set the LATERAL expressions.
2777
2778        Example:
2779            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2780            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2781
2782        Args:
2783            *expressions: the SQL code strings to parse.
2784                If an `Expression` instance is passed, it will be used as-is.
2785            append: if `True`, add to any existing expressions.
2786                Otherwise, this resets the expressions.
2787            dialect: the dialect used to parse the input expressions.
2788            copy: if `False`, modify this expression instance in-place.
2789            opts: other options to use to parse the input expressions.
2790
2791        Returns:
2792            The modified Select expression.
2793        """
2794        return _apply_list_builder(
2795            *expressions,
2796            instance=self,
2797            arg="laterals",
2798            append=append,
2799            into=Lateral,
2800            prefix="LATERAL VIEW",
2801            dialect=dialect,
2802            copy=copy,
2803            **opts,
2804        )
2805
2806    def join(
2807        self,
2808        expression: ExpOrStr,
2809        on: t.Optional[ExpOrStr] = None,
2810        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2811        append: bool = True,
2812        join_type: t.Optional[str] = None,
2813        join_alias: t.Optional[Identifier | str] = None,
2814        dialect: DialectType = None,
2815        copy: bool = True,
2816        **opts,
2817    ) -> Select:
2818        """
2819        Append to or set the JOIN expressions.
2820
2821        Example:
2822            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2823            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2824
2825            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2826            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2827
2828            Use `join_type` to change the type of join:
2829
2830            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2831            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2832
2833        Args:
2834            expression: the SQL code string to parse.
2835                If an `Expression` instance is passed, it will be used as-is.
2836            on: optionally specify the join "on" criteria as a SQL string.
2837                If an `Expression` instance is passed, it will be used as-is.
2838            using: optionally specify the join "using" criteria as a SQL string.
2839                If an `Expression` instance is passed, it will be used as-is.
2840            append: if `True`, add to any existing expressions.
2841                Otherwise, this resets the expressions.
2842            join_type: if set, alter the parsed join type.
2843            join_alias: an optional alias for the joined source.
2844            dialect: the dialect used to parse the input expressions.
2845            copy: if `False`, modify this expression instance in-place.
2846            opts: other options to use to parse the input expressions.
2847
2848        Returns:
2849            Select: the modified expression.
2850        """
2851        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2852
2853        try:
2854            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2855        except ParseError:
2856            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2857
2858        join = expression if isinstance(expression, Join) else Join(this=expression)
2859
2860        if isinstance(join.this, Select):
2861            join.this.replace(join.this.subquery())
2862
2863        if join_type:
2864            method: t.Optional[Token]
2865            side: t.Optional[Token]
2866            kind: t.Optional[Token]
2867
2868            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2869
2870            if method:
2871                join.set("method", method.text)
2872            if side:
2873                join.set("side", side.text)
2874            if kind:
2875                join.set("kind", kind.text)
2876
2877        if on:
2878            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2879            join.set("on", on)
2880
2881        if using:
2882            join = _apply_list_builder(
2883                *ensure_list(using),
2884                instance=join,
2885                arg="using",
2886                append=append,
2887                copy=copy,
2888                **opts,
2889            )
2890
2891        if join_alias:
2892            join.set("this", alias_(join.this, join_alias, table=True))
2893
2894        return _apply_list_builder(
2895            join,
2896            instance=self,
2897            arg="joins",
2898            append=append,
2899            copy=copy,
2900            **opts,
2901        )
2902
2903    def where(
2904        self,
2905        *expressions: t.Optional[ExpOrStr],
2906        append: bool = True,
2907        dialect: DialectType = None,
2908        copy: bool = True,
2909        **opts,
2910    ) -> Select:
2911        """
2912        Append to or set the WHERE expressions.
2913
2914        Example:
2915            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2916            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2917
2918        Args:
2919            *expressions: the SQL code strings to parse.
2920                If an `Expression` instance is passed, it will be used as-is.
2921                Multiple expressions are combined with an AND operator.
2922            append: if `True`, AND the new expressions to any existing expression.
2923                Otherwise, this resets the expression.
2924            dialect: the dialect used to parse the input expressions.
2925            copy: if `False`, modify this expression instance in-place.
2926            opts: other options to use to parse the input expressions.
2927
2928        Returns:
2929            Select: the modified expression.
2930        """
2931        return _apply_conjunction_builder(
2932            *expressions,
2933            instance=self,
2934            arg="where",
2935            append=append,
2936            into=Where,
2937            dialect=dialect,
2938            copy=copy,
2939            **opts,
2940        )
2941
2942    def having(
2943        self,
2944        *expressions: t.Optional[ExpOrStr],
2945        append: bool = True,
2946        dialect: DialectType = None,
2947        copy: bool = True,
2948        **opts,
2949    ) -> Select:
2950        """
2951        Append to or set the HAVING expressions.
2952
2953        Example:
2954            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2955            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2956
2957        Args:
2958            *expressions: the SQL code strings to parse.
2959                If an `Expression` instance is passed, it will be used as-is.
2960                Multiple expressions are combined with an AND operator.
2961            append: if `True`, AND the new expressions to any existing expression.
2962                Otherwise, this resets the expression.
2963            dialect: the dialect used to parse the input expressions.
2964            copy: if `False`, modify this expression instance in-place.
2965            opts: other options to use to parse the input expressions.
2966
2967        Returns:
2968            The modified Select expression.
2969        """
2970        return _apply_conjunction_builder(
2971            *expressions,
2972            instance=self,
2973            arg="having",
2974            append=append,
2975            into=Having,
2976            dialect=dialect,
2977            copy=copy,
2978            **opts,
2979        )
2980
2981    def window(
2982        self,
2983        *expressions: t.Optional[ExpOrStr],
2984        append: bool = True,
2985        dialect: DialectType = None,
2986        copy: bool = True,
2987        **opts,
2988    ) -> Select:
2989        return _apply_list_builder(
2990            *expressions,
2991            instance=self,
2992            arg="windows",
2993            append=append,
2994            into=Window,
2995            dialect=dialect,
2996            copy=copy,
2997            **opts,
2998        )
2999
3000    def qualify(
3001        self,
3002        *expressions: t.Optional[ExpOrStr],
3003        append: bool = True,
3004        dialect: DialectType = None,
3005        copy: bool = True,
3006        **opts,
3007    ) -> Select:
3008        return _apply_conjunction_builder(
3009            *expressions,
3010            instance=self,
3011            arg="qualify",
3012            append=append,
3013            into=Qualify,
3014            dialect=dialect,
3015            copy=copy,
3016            **opts,
3017        )
3018
3019    def distinct(
3020        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3021    ) -> Select:
3022        """
3023        Set the OFFSET expression.
3024
3025        Example:
3026            >>> Select().from_("tbl").select("x").distinct().sql()
3027            'SELECT DISTINCT x FROM tbl'
3028
3029        Args:
3030            ons: the expressions to distinct on
3031            distinct: whether the Select should be distinct
3032            copy: if `False`, modify this expression instance in-place.
3033
3034        Returns:
3035            Select: the modified expression.
3036        """
3037        instance = _maybe_copy(self, copy)
3038        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3039        instance.set("distinct", Distinct(on=on) if distinct else None)
3040        return instance
3041
3042    def ctas(
3043        self,
3044        table: ExpOrStr,
3045        properties: t.Optional[t.Dict] = None,
3046        dialect: DialectType = None,
3047        copy: bool = True,
3048        **opts,
3049    ) -> Create:
3050        """
3051        Convert this expression to a CREATE TABLE AS statement.
3052
3053        Example:
3054            >>> Select().select("*").from_("tbl").ctas("x").sql()
3055            'CREATE TABLE x AS SELECT * FROM tbl'
3056
3057        Args:
3058            table: the SQL code string to parse as the table name.
3059                If another `Expression` instance is passed, it will be used as-is.
3060            properties: an optional mapping of table properties
3061            dialect: the dialect used to parse the input table.
3062            copy: if `False`, modify this expression instance in-place.
3063            opts: other options to use to parse the input table.
3064
3065        Returns:
3066            The new Create expression.
3067        """
3068        instance = _maybe_copy(self, copy)
3069        table_expression = maybe_parse(
3070            table,
3071            into=Table,
3072            dialect=dialect,
3073            **opts,
3074        )
3075        properties_expression = None
3076        if properties:
3077            properties_expression = Properties.from_dict(properties)
3078
3079        return Create(
3080            this=table_expression,
3081            kind="table",
3082            expression=instance,
3083            properties=properties_expression,
3084        )
3085
3086    def lock(self, update: bool = True, copy: bool = True) -> Select:
3087        """
3088        Set the locking read mode for this expression.
3089
3090        Examples:
3091            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3092            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3093
3094            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3095            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3096
3097        Args:
3098            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3099            copy: if `False`, modify this expression instance in-place.
3100
3101        Returns:
3102            The modified expression.
3103        """
3104        inst = _maybe_copy(self, copy)
3105        inst.set("locks", [Lock(update=update)])
3106
3107        return inst
3108
3109    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3110        """
3111        Set hints for this expression.
3112
3113        Examples:
3114            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3115            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3116
3117        Args:
3118            hints: The SQL code strings to parse as the hints.
3119                If an `Expression` instance is passed, it will be used as-is.
3120            dialect: The dialect used to parse the hints.
3121            copy: If `False`, modify this expression instance in-place.
3122
3123        Returns:
3124            The modified expression.
3125        """
3126        inst = _maybe_copy(self, copy)
3127        inst.set(
3128            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3129        )
3130
3131        return inst
3132
3133    @property
3134    def named_selects(self) -> t.List[str]:
3135        return [e.output_name for e in self.expressions if e.alias_or_name]
3136
3137    @property
3138    def is_star(self) -> bool:
3139        return any(expression.is_star for expression in self.expressions)
3140
3141    @property
3142    def selects(self) -> t.List[Expression]:
3143        return self.expressions
arg_types = {'with': False, 'kind': False, 'expressions': False, 'hint': False, 'distinct': False, 'into': False, 'from': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def from_( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2468    def from_(
2469        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2470    ) -> Select:
2471        """
2472        Set the FROM expression.
2473
2474        Example:
2475            >>> Select().from_("tbl").select("x").sql()
2476            'SELECT x FROM tbl'
2477
2478        Args:
2479            expression : the SQL code strings to parse.
2480                If a `From` instance is passed, this is used as-is.
2481                If another `Expression` instance is passed, it will be wrapped in a `From`.
2482            dialect: the dialect used to parse the input expression.
2483            copy: if `False`, modify this expression instance in-place.
2484            opts: other options to use to parse the input expressions.
2485
2486        Returns:
2487            The modified Select expression.
2488        """
2489        return _apply_builder(
2490            expression=expression,
2491            instance=self,
2492            arg="from",
2493            into=From,
2494            prefix="FROM",
2495            dialect=dialect,
2496            copy=copy,
2497            **opts,
2498        )

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • expression : the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def group_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2500    def group_by(
2501        self,
2502        *expressions: t.Optional[ExpOrStr],
2503        append: bool = True,
2504        dialect: DialectType = None,
2505        copy: bool = True,
2506        **opts,
2507    ) -> Select:
2508        """
2509        Set the GROUP BY expression.
2510
2511        Example:
2512            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2513            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2514
2515        Args:
2516            *expressions: the SQL code strings to parse.
2517                If a `Group` instance is passed, this is used as-is.
2518                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2519                If nothing is passed in then a group by is not applied to the expression
2520            append: if `True`, add to any existing expressions.
2521                Otherwise, this flattens all the `Group` expression into a single expression.
2522            dialect: the dialect used to parse the input expression.
2523            copy: if `False`, modify this expression instance in-place.
2524            opts: other options to use to parse the input expressions.
2525
2526        Returns:
2527            The modified Select expression.
2528        """
2529        if not expressions:
2530            return self if not copy else self.copy()
2531
2532        return _apply_child_list_builder(
2533            *expressions,
2534            instance=self,
2535            arg="group",
2536            append=append,
2537            copy=copy,
2538            prefix="GROUP BY",
2539            into=Group,
2540            dialect=dialect,
2541            **opts,
2542        )

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def order_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2544    def order_by(
2545        self,
2546        *expressions: t.Optional[ExpOrStr],
2547        append: bool = True,
2548        dialect: DialectType = None,
2549        copy: bool = True,
2550        **opts,
2551    ) -> Select:
2552        """
2553        Set the ORDER BY expression.
2554
2555        Example:
2556            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2557            'SELECT x FROM tbl ORDER BY x DESC'
2558
2559        Args:
2560            *expressions: the SQL code strings to parse.
2561                If a `Group` instance is passed, this is used as-is.
2562                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2563            append: if `True`, add to any existing expressions.
2564                Otherwise, this flattens all the `Order` expression into a single expression.
2565            dialect: the dialect used to parse the input expression.
2566            copy: if `False`, modify this expression instance in-place.
2567            opts: other options to use to parse the input expressions.
2568
2569        Returns:
2570            The modified Select expression.
2571        """
2572        return _apply_child_list_builder(
2573            *expressions,
2574            instance=self,
2575            arg="order",
2576            append=append,
2577            copy=copy,
2578            prefix="ORDER BY",
2579            into=Order,
2580            dialect=dialect,
2581            **opts,
2582        )

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def sort_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2584    def sort_by(
2585        self,
2586        *expressions: t.Optional[ExpOrStr],
2587        append: bool = True,
2588        dialect: DialectType = None,
2589        copy: bool = True,
2590        **opts,
2591    ) -> Select:
2592        """
2593        Set the SORT BY expression.
2594
2595        Example:
2596            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2597            'SELECT x FROM tbl SORT BY x DESC'
2598
2599        Args:
2600            *expressions: the SQL code strings to parse.
2601                If a `Group` instance is passed, this is used as-is.
2602                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2603            append: if `True`, add to any existing expressions.
2604                Otherwise, this flattens all the `Order` expression into a single expression.
2605            dialect: the dialect used to parse the input expression.
2606            copy: if `False`, modify this expression instance in-place.
2607            opts: other options to use to parse the input expressions.
2608
2609        Returns:
2610            The modified Select expression.
2611        """
2612        return _apply_child_list_builder(
2613            *expressions,
2614            instance=self,
2615            arg="sort",
2616            append=append,
2617            copy=copy,
2618            prefix="SORT BY",
2619            into=Sort,
2620            dialect=dialect,
2621            **opts,
2622        )

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def cluster_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2624    def cluster_by(
2625        self,
2626        *expressions: t.Optional[ExpOrStr],
2627        append: bool = True,
2628        dialect: DialectType = None,
2629        copy: bool = True,
2630        **opts,
2631    ) -> Select:
2632        """
2633        Set the CLUSTER BY expression.
2634
2635        Example:
2636            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2637            'SELECT x FROM tbl CLUSTER BY x DESC'
2638
2639        Args:
2640            *expressions: the SQL code strings to parse.
2641                If a `Group` instance is passed, this is used as-is.
2642                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2643            append: if `True`, add to any existing expressions.
2644                Otherwise, this flattens all the `Order` expression into a single expression.
2645            dialect: the dialect used to parse the input expression.
2646            copy: if `False`, modify this expression instance in-place.
2647            opts: other options to use to parse the input expressions.
2648
2649        Returns:
2650            The modified Select expression.
2651        """
2652        return _apply_child_list_builder(
2653            *expressions,
2654            instance=self,
2655            arg="cluster",
2656            append=append,
2657            copy=copy,
2658            prefix="CLUSTER BY",
2659            into=Cluster,
2660            dialect=dialect,
2661            **opts,
2662        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2664    def limit(
2665        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2666    ) -> Select:
2667        """
2668        Set the LIMIT expression.
2669
2670        Example:
2671            >>> Select().from_("tbl").select("x").limit(10).sql()
2672            'SELECT x FROM tbl LIMIT 10'
2673
2674        Args:
2675            expression: the SQL code string to parse.
2676                This can also be an integer.
2677                If a `Limit` instance is passed, this is used as-is.
2678                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2679            dialect: the dialect used to parse the input expression.
2680            copy: if `False`, modify this expression instance in-place.
2681            opts: other options to use to parse the input expressions.
2682
2683        Returns:
2684            Select: the modified expression.
2685        """
2686        return _apply_builder(
2687            expression=expression,
2688            instance=self,
2689            arg="limit",
2690            into=Limit,
2691            prefix="LIMIT",
2692            dialect=dialect,
2693            copy=copy,
2694            **opts,
2695        )

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def offset( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2697    def offset(
2698        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2699    ) -> Select:
2700        """
2701        Set the OFFSET expression.
2702
2703        Example:
2704            >>> Select().from_("tbl").select("x").offset(10).sql()
2705            'SELECT x FROM tbl OFFSET 10'
2706
2707        Args:
2708            expression: the SQL code string to parse.
2709                This can also be an integer.
2710                If a `Offset` instance is passed, this is used as-is.
2711                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2712            dialect: the dialect used to parse the input expression.
2713            copy: if `False`, modify this expression instance in-place.
2714            opts: other options to use to parse the input expressions.
2715
2716        Returns:
2717            The modified Select expression.
2718        """
2719        return _apply_builder(
2720            expression=expression,
2721            instance=self,
2722            arg="offset",
2723            into=Offset,
2724            prefix="OFFSET",
2725            dialect=dialect,
2726            copy=copy,
2727            **opts,
2728        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2730    def select(
2731        self,
2732        *expressions: t.Optional[ExpOrStr],
2733        append: bool = True,
2734        dialect: DialectType = None,
2735        copy: bool = True,
2736        **opts,
2737    ) -> Select:
2738        """
2739        Append to or set the SELECT expressions.
2740
2741        Example:
2742            >>> Select().select("x", "y").sql()
2743            'SELECT x, y'
2744
2745        Args:
2746            *expressions: the SQL code strings to parse.
2747                If an `Expression` instance is passed, it will be used as-is.
2748            append: if `True`, add to any existing expressions.
2749                Otherwise, this resets the expressions.
2750            dialect: the dialect used to parse the input expressions.
2751            copy: if `False`, modify this expression instance in-place.
2752            opts: other options to use to parse the input expressions.
2753
2754        Returns:
2755            The modified Select expression.
2756        """
2757        return _apply_list_builder(
2758            *expressions,
2759            instance=self,
2760            arg="expressions",
2761            append=append,
2762            dialect=dialect,
2763            copy=copy,
2764            **opts,
2765        )

Append to or set the SELECT expressions.

Example:
>>> Select().select("x", "y").sql()
'SELECT x, y'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def lateral( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2767    def lateral(
2768        self,
2769        *expressions: t.Optional[ExpOrStr],
2770        append: bool = True,
2771        dialect: DialectType = None,
2772        copy: bool = True,
2773        **opts,
2774    ) -> Select:
2775        """
2776        Append to or set the LATERAL expressions.
2777
2778        Example:
2779            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2780            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2781
2782        Args:
2783            *expressions: the SQL code strings to parse.
2784                If an `Expression` instance is passed, it will be used as-is.
2785            append: if `True`, add to any existing expressions.
2786                Otherwise, this resets the expressions.
2787            dialect: the dialect used to parse the input expressions.
2788            copy: if `False`, modify this expression instance in-place.
2789            opts: other options to use to parse the input expressions.
2790
2791        Returns:
2792            The modified Select expression.
2793        """
2794        return _apply_list_builder(
2795            *expressions,
2796            instance=self,
2797            arg="laterals",
2798            append=append,
2799            into=Lateral,
2800            prefix="LATERAL VIEW",
2801            dialect=dialect,
2802            copy=copy,
2803            **opts,
2804        )

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def join( self, expression: Union[str, sqlglot.expressions.Expression], on: Union[str, sqlglot.expressions.Expression, NoneType] = None, using: Union[str, sqlglot.expressions.Expression, List[Union[str, sqlglot.expressions.Expression]], NoneType] = None, append: bool = True, join_type: Optional[str] = None, join_alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2806    def join(
2807        self,
2808        expression: ExpOrStr,
2809        on: t.Optional[ExpOrStr] = None,
2810        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2811        append: bool = True,
2812        join_type: t.Optional[str] = None,
2813        join_alias: t.Optional[Identifier | str] = None,
2814        dialect: DialectType = None,
2815        copy: bool = True,
2816        **opts,
2817    ) -> Select:
2818        """
2819        Append to or set the JOIN expressions.
2820
2821        Example:
2822            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2823            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2824
2825            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2826            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2827
2828            Use `join_type` to change the type of join:
2829
2830            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2831            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2832
2833        Args:
2834            expression: the SQL code string to parse.
2835                If an `Expression` instance is passed, it will be used as-is.
2836            on: optionally specify the join "on" criteria as a SQL string.
2837                If an `Expression` instance is passed, it will be used as-is.
2838            using: optionally specify the join "using" criteria as a SQL string.
2839                If an `Expression` instance is passed, it will be used as-is.
2840            append: if `True`, add to any existing expressions.
2841                Otherwise, this resets the expressions.
2842            join_type: if set, alter the parsed join type.
2843            join_alias: an optional alias for the joined source.
2844            dialect: the dialect used to parse the input expressions.
2845            copy: if `False`, modify this expression instance in-place.
2846            opts: other options to use to parse the input expressions.
2847
2848        Returns:
2849            Select: the modified expression.
2850        """
2851        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2852
2853        try:
2854            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2855        except ParseError:
2856            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2857
2858        join = expression if isinstance(expression, Join) else Join(this=expression)
2859
2860        if isinstance(join.this, Select):
2861            join.this.replace(join.this.subquery())
2862
2863        if join_type:
2864            method: t.Optional[Token]
2865            side: t.Optional[Token]
2866            kind: t.Optional[Token]
2867
2868            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2869
2870            if method:
2871                join.set("method", method.text)
2872            if side:
2873                join.set("side", side.text)
2874            if kind:
2875                join.set("kind", kind.text)
2876
2877        if on:
2878            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2879            join.set("on", on)
2880
2881        if using:
2882            join = _apply_list_builder(
2883                *ensure_list(using),
2884                instance=join,
2885                arg="using",
2886                append=append,
2887                copy=copy,
2888                **opts,
2889            )
2890
2891        if join_alias:
2892            join.set("this", alias_(join.this, join_alias, table=True))
2893
2894        return _apply_list_builder(
2895            join,
2896            instance=self,
2897            arg="joins",
2898            append=append,
2899            copy=copy,
2900            **opts,
2901        )

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on: optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using: optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type: if set, alter the parsed join type.
  • join_alias: an optional alias for the joined source.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2903    def where(
2904        self,
2905        *expressions: t.Optional[ExpOrStr],
2906        append: bool = True,
2907        dialect: DialectType = None,
2908        copy: bool = True,
2909        **opts,
2910    ) -> Select:
2911        """
2912        Append to or set the WHERE expressions.
2913
2914        Example:
2915            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2916            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2917
2918        Args:
2919            *expressions: the SQL code strings to parse.
2920                If an `Expression` instance is passed, it will be used as-is.
2921                Multiple expressions are combined with an AND operator.
2922            append: if `True`, AND the new expressions to any existing expression.
2923                Otherwise, this resets the expression.
2924            dialect: the dialect used to parse the input expressions.
2925            copy: if `False`, modify this expression instance in-place.
2926            opts: other options to use to parse the input expressions.
2927
2928        Returns:
2929            Select: the modified expression.
2930        """
2931        return _apply_conjunction_builder(
2932            *expressions,
2933            instance=self,
2934            arg="where",
2935            append=append,
2936            into=Where,
2937            dialect=dialect,
2938            copy=copy,
2939            **opts,
2940        )

Append to or set the WHERE expressions.

Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2942    def having(
2943        self,
2944        *expressions: t.Optional[ExpOrStr],
2945        append: bool = True,
2946        dialect: DialectType = None,
2947        copy: bool = True,
2948        **opts,
2949    ) -> Select:
2950        """
2951        Append to or set the HAVING expressions.
2952
2953        Example:
2954            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2955            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2956
2957        Args:
2958            *expressions: the SQL code strings to parse.
2959                If an `Expression` instance is passed, it will be used as-is.
2960                Multiple expressions are combined with an AND operator.
2961            append: if `True`, AND the new expressions to any existing expression.
2962                Otherwise, this resets the expression.
2963            dialect: the dialect used to parse the input expressions.
2964            copy: if `False`, modify this expression instance in-place.
2965            opts: other options to use to parse the input expressions.
2966
2967        Returns:
2968            The modified Select expression.
2969        """
2970        return _apply_conjunction_builder(
2971            *expressions,
2972            instance=self,
2973            arg="having",
2974            append=append,
2975            into=Having,
2976            dialect=dialect,
2977            copy=copy,
2978            **opts,
2979        )

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def window( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2981    def window(
2982        self,
2983        *expressions: t.Optional[ExpOrStr],
2984        append: bool = True,
2985        dialect: DialectType = None,
2986        copy: bool = True,
2987        **opts,
2988    ) -> Select:
2989        return _apply_list_builder(
2990            *expressions,
2991            instance=self,
2992            arg="windows",
2993            append=append,
2994            into=Window,
2995            dialect=dialect,
2996            copy=copy,
2997            **opts,
2998        )
def qualify( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
3000    def qualify(
3001        self,
3002        *expressions: t.Optional[ExpOrStr],
3003        append: bool = True,
3004        dialect: DialectType = None,
3005        copy: bool = True,
3006        **opts,
3007    ) -> Select:
3008        return _apply_conjunction_builder(
3009            *expressions,
3010            instance=self,
3011            arg="qualify",
3012            append=append,
3013            into=Qualify,
3014            dialect=dialect,
3015            copy=copy,
3016            **opts,
3017        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression, NoneType], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3019    def distinct(
3020        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3021    ) -> Select:
3022        """
3023        Set the OFFSET expression.
3024
3025        Example:
3026            >>> Select().from_("tbl").select("x").distinct().sql()
3027            'SELECT DISTINCT x FROM tbl'
3028
3029        Args:
3030            ons: the expressions to distinct on
3031            distinct: whether the Select should be distinct
3032            copy: if `False`, modify this expression instance in-place.
3033
3034        Returns:
3035            Select: the modified expression.
3036        """
3037        instance = _maybe_copy(self, copy)
3038        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3039        instance.set("distinct", Distinct(on=on) if distinct else None)
3040        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • ons: the expressions to distinct on
  • distinct: whether the Select should be distinct
  • copy: if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table: Union[str, sqlglot.expressions.Expression], properties: Optional[Dict] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Create:
3042    def ctas(
3043        self,
3044        table: ExpOrStr,
3045        properties: t.Optional[t.Dict] = None,
3046        dialect: DialectType = None,
3047        copy: bool = True,
3048        **opts,
3049    ) -> Create:
3050        """
3051        Convert this expression to a CREATE TABLE AS statement.
3052
3053        Example:
3054            >>> Select().select("*").from_("tbl").ctas("x").sql()
3055            'CREATE TABLE x AS SELECT * FROM tbl'
3056
3057        Args:
3058            table: the SQL code string to parse as the table name.
3059                If another `Expression` instance is passed, it will be used as-is.
3060            properties: an optional mapping of table properties
3061            dialect: the dialect used to parse the input table.
3062            copy: if `False`, modify this expression instance in-place.
3063            opts: other options to use to parse the input table.
3064
3065        Returns:
3066            The new Create expression.
3067        """
3068        instance = _maybe_copy(self, copy)
3069        table_expression = maybe_parse(
3070            table,
3071            into=Table,
3072            dialect=dialect,
3073            **opts,
3074        )
3075        properties_expression = None
3076        if properties:
3077            properties_expression = Properties.from_dict(properties)
3078
3079        return Create(
3080            this=table_expression,
3081            kind="table",
3082            expression=instance,
3083            properties=properties_expression,
3084        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table: the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties: an optional mapping of table properties
  • dialect: the dialect used to parse the input table.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input table.
Returns:

The new Create expression.

def lock( self, update: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3086    def lock(self, update: bool = True, copy: bool = True) -> Select:
3087        """
3088        Set the locking read mode for this expression.
3089
3090        Examples:
3091            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3092            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3093
3094            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3095            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3096
3097        Args:
3098            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3099            copy: if `False`, modify this expression instance in-place.
3100
3101        Returns:
3102            The modified expression.
3103        """
3104        inst = _maybe_copy(self, copy)
3105        inst.set("locks", [Lock(update=update)])
3106
3107        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

def hint( self, *hints: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True) -> sqlglot.expressions.Select:
3109    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3110        """
3111        Set hints for this expression.
3112
3113        Examples:
3114            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3115            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3116
3117        Args:
3118            hints: The SQL code strings to parse as the hints.
3119                If an `Expression` instance is passed, it will be used as-is.
3120            dialect: The dialect used to parse the hints.
3121            copy: If `False`, modify this expression instance in-place.
3122
3123        Returns:
3124            The modified expression.
3125        """
3126        inst = _maybe_copy(self, copy)
3127        inst.set(
3128            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3129        )
3130
3131        return inst

Set hints for this expression.

Examples:
>>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
'SELECT /*+ BROADCAST(y) */ x FROM tbl'
Arguments:
  • hints: The SQL code strings to parse as the hints. If an Expression instance is passed, it will be used as-is.
  • dialect: The dialect used to parse the hints.
  • copy: If False, modify this expression instance in-place.
Returns:

The modified expression.

named_selects: List[str]
is_star: bool

Checks whether an expression is a star.

key = 'select'
class Subquery(DerivedTable, Unionable):
3146class Subquery(DerivedTable, Unionable):
3147    arg_types = {
3148        "this": True,
3149        "alias": False,
3150        "with": False,
3151        **QUERY_MODIFIERS,
3152    }
3153
3154    def unnest(self):
3155        """
3156        Returns the first non subquery.
3157        """
3158        expression = self
3159        while isinstance(expression, Subquery):
3160            expression = expression.this
3161        return expression
3162
3163    @property
3164    def is_star(self) -> bool:
3165        return self.this.is_star
3166
3167    @property
3168    def output_name(self) -> str:
3169        return self.alias
arg_types = {'this': True, 'alias': False, 'with': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def unnest(self):
3154    def unnest(self):
3155        """
3156        Returns the first non subquery.
3157        """
3158        expression = self
3159        while isinstance(expression, Subquery):
3160            expression = expression.this
3161        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'subquery'
class TableSample(Expression):
3172class TableSample(Expression):
3173    arg_types = {
3174        "this": False,
3175        "method": False,
3176        "bucket_numerator": False,
3177        "bucket_denominator": False,
3178        "bucket_field": False,
3179        "percent": False,
3180        "rows": False,
3181        "size": False,
3182        "seed": False,
3183        "kind": False,
3184    }
arg_types = {'this': False, 'method': False, 'bucket_numerator': False, 'bucket_denominator': False, 'bucket_field': False, 'percent': False, 'rows': False, 'size': False, 'seed': False, 'kind': False}
key = 'tablesample'
class Tag(Expression):
3187class Tag(Expression):
3188    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3189
3190    arg_types = {
3191        "this": False,
3192        "prefix": False,
3193        "postfix": False,
3194    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3199class Pivot(Expression):
3200    arg_types = {
3201        "this": False,
3202        "alias": False,
3203        "expressions": True,
3204        "field": False,
3205        "unpivot": False,
3206        "using": False,
3207        "group": False,
3208        "columns": False,
3209    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False}
key = 'pivot'
class Window(Expression):
3212class Window(Expression):
3213    arg_types = {
3214        "this": True,
3215        "partition_by": False,
3216        "order": False,
3217        "spec": False,
3218        "alias": False,
3219        "over": False,
3220        "first": False,
3221    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3224class WindowSpec(Expression):
3225    arg_types = {
3226        "kind": False,
3227        "start": False,
3228        "start_side": False,
3229        "end": False,
3230        "end_side": False,
3231    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3234class Where(Expression):
3235    pass
key = 'where'
class Star(Expression):
3238class Star(Expression):
3239    arg_types = {"except": False, "replace": False}
3240
3241    @property
3242    def name(self) -> str:
3243        return "*"
3244
3245    @property
3246    def output_name(self) -> str:
3247        return self.name
arg_types = {'except': False, 'replace': False}
name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'star'
class Parameter(Condition):
3250class Parameter(Condition):
3251    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3254class SessionParameter(Condition):
3255    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3258class Placeholder(Condition):
3259    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3262class Null(Condition):
3263    arg_types: t.Dict[str, t.Any] = {}
3264
3265    @property
3266    def name(self) -> str:
3267        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3270class Boolean(Condition):
3271    pass
key = 'boolean'
class DataTypeSize(Expression):
3274class DataTypeSize(Expression):
3275    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
3278class DataType(Expression):
3279    arg_types = {
3280        "this": True,
3281        "expressions": False,
3282        "nested": False,
3283        "values": False,
3284        "prefix": False,
3285    }
3286
3287    class Type(AutoName):
3288        ARRAY = auto()
3289        BIGDECIMAL = auto()
3290        BIGINT = auto()
3291        BIGSERIAL = auto()
3292        BINARY = auto()
3293        BIT = auto()
3294        BOOLEAN = auto()
3295        CHAR = auto()
3296        DATE = auto()
3297        DATETIME = auto()
3298        DATETIME64 = auto()
3299        ENUM = auto()
3300        INT4RANGE = auto()
3301        INT4MULTIRANGE = auto()
3302        INT8RANGE = auto()
3303        INT8MULTIRANGE = auto()
3304        NUMRANGE = auto()
3305        NUMMULTIRANGE = auto()
3306        TSRANGE = auto()
3307        TSMULTIRANGE = auto()
3308        TSTZRANGE = auto()
3309        TSTZMULTIRANGE = auto()
3310        DATERANGE = auto()
3311        DATEMULTIRANGE = auto()
3312        DECIMAL = auto()
3313        DOUBLE = auto()
3314        FLOAT = auto()
3315        GEOGRAPHY = auto()
3316        GEOMETRY = auto()
3317        HLLSKETCH = auto()
3318        HSTORE = auto()
3319        IMAGE = auto()
3320        INET = auto()
3321        INT = auto()
3322        INT128 = auto()
3323        INT256 = auto()
3324        INTERVAL = auto()
3325        JSON = auto()
3326        JSONB = auto()
3327        LONGBLOB = auto()
3328        LONGTEXT = auto()
3329        MAP = auto()
3330        MEDIUMBLOB = auto()
3331        MEDIUMTEXT = auto()
3332        MONEY = auto()
3333        NCHAR = auto()
3334        NULL = auto()
3335        NULLABLE = auto()
3336        NVARCHAR = auto()
3337        OBJECT = auto()
3338        ROWVERSION = auto()
3339        SERIAL = auto()
3340        SET = auto()
3341        SMALLINT = auto()
3342        SMALLMONEY = auto()
3343        SMALLSERIAL = auto()
3344        STRUCT = auto()
3345        SUPER = auto()
3346        TEXT = auto()
3347        TIME = auto()
3348        TIMESTAMP = auto()
3349        TIMESTAMPTZ = auto()
3350        TIMESTAMPLTZ = auto()
3351        TINYINT = auto()
3352        UBIGINT = auto()
3353        UINT = auto()
3354        USMALLINT = auto()
3355        UTINYINT = auto()
3356        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3357        UINT128 = auto()
3358        UINT256 = auto()
3359        UNIQUEIDENTIFIER = auto()
3360        USERDEFINED = "USER-DEFINED"
3361        UUID = auto()
3362        VARBINARY = auto()
3363        VARCHAR = auto()
3364        VARIANT = auto()
3365        XML = auto()
3366
3367    TEXT_TYPES = {
3368        Type.CHAR,
3369        Type.NCHAR,
3370        Type.VARCHAR,
3371        Type.NVARCHAR,
3372        Type.TEXT,
3373    }
3374
3375    INTEGER_TYPES = {
3376        Type.INT,
3377        Type.TINYINT,
3378        Type.SMALLINT,
3379        Type.BIGINT,
3380        Type.INT128,
3381        Type.INT256,
3382    }
3383
3384    FLOAT_TYPES = {
3385        Type.FLOAT,
3386        Type.DOUBLE,
3387    }
3388
3389    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3390
3391    TEMPORAL_TYPES = {
3392        Type.TIME,
3393        Type.TIMESTAMP,
3394        Type.TIMESTAMPTZ,
3395        Type.TIMESTAMPLTZ,
3396        Type.DATE,
3397        Type.DATETIME,
3398        Type.DATETIME64,
3399    }
3400
3401    META_TYPES = {"UNKNOWN", "NULL"}
3402
3403    @classmethod
3404    def build(
3405        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3406    ) -> DataType:
3407        from sqlglot import parse_one
3408
3409        if isinstance(dtype, str):
3410            upper = dtype.upper()
3411            if upper in DataType.META_TYPES:
3412                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3413            else:
3414                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3415
3416            if data_type_exp is None:
3417                raise ValueError(f"Unparsable data type value: {dtype}")
3418        elif isinstance(dtype, DataType.Type):
3419            data_type_exp = DataType(this=dtype)
3420        elif isinstance(dtype, DataType):
3421            return dtype
3422        else:
3423            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3424
3425        return DataType(**{**data_type_exp.args, **kwargs})
3426
3427    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3428        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False}
TEXT_TYPES = {<Type.NVARCHAR: 'NVARCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.TEXT: 'TEXT'>, <Type.CHAR: 'CHAR'>, <Type.NCHAR: 'NCHAR'>}
INTEGER_TYPES = {<Type.TINYINT: 'TINYINT'>, <Type.BIGINT: 'BIGINT'>, <Type.INT128: 'INT128'>, <Type.INT256: 'INT256'>, <Type.INT: 'INT'>, <Type.SMALLINT: 'SMALLINT'>}
FLOAT_TYPES = {<Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>}
NUMERIC_TYPES = {<Type.TINYINT: 'TINYINT'>, <Type.INT256: 'INT256'>, <Type.BIGINT: 'BIGINT'>, <Type.INT: 'INT'>, <Type.DOUBLE: 'DOUBLE'>, <Type.INT128: 'INT128'>, <Type.FLOAT: 'FLOAT'>, <Type.SMALLINT: 'SMALLINT'>}
TEMPORAL_TYPES = {<Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.DATETIME64: 'DATETIME64'>, <Type.DATE: 'DATE'>, <Type.DATETIME: 'DATETIME'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.TIME: 'TIME'>}
META_TYPES = {'UNKNOWN', 'NULL'}
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
3403    @classmethod
3404    def build(
3405        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3406    ) -> DataType:
3407        from sqlglot import parse_one
3408
3409        if isinstance(dtype, str):
3410            upper = dtype.upper()
3411            if upper in DataType.META_TYPES:
3412                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3413            else:
3414                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3415
3416            if data_type_exp is None:
3417                raise ValueError(f"Unparsable data type value: {dtype}")
3418        elif isinstance(dtype, DataType.Type):
3419            data_type_exp = DataType(this=dtype)
3420        elif isinstance(dtype, DataType):
3421            return dtype
3422        else:
3423            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3424
3425        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3427    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3428        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3287    class Type(AutoName):
3288        ARRAY = auto()
3289        BIGDECIMAL = auto()
3290        BIGINT = auto()
3291        BIGSERIAL = auto()
3292        BINARY = auto()
3293        BIT = auto()
3294        BOOLEAN = auto()
3295        CHAR = auto()
3296        DATE = auto()
3297        DATETIME = auto()
3298        DATETIME64 = auto()
3299        ENUM = auto()
3300        INT4RANGE = auto()
3301        INT4MULTIRANGE = auto()
3302        INT8RANGE = auto()
3303        INT8MULTIRANGE = auto()
3304        NUMRANGE = auto()
3305        NUMMULTIRANGE = auto()
3306        TSRANGE = auto()
3307        TSMULTIRANGE = auto()
3308        TSTZRANGE = auto()
3309        TSTZMULTIRANGE = auto()
3310        DATERANGE = auto()
3311        DATEMULTIRANGE = auto()
3312        DECIMAL = auto()
3313        DOUBLE = auto()
3314        FLOAT = auto()
3315        GEOGRAPHY = auto()
3316        GEOMETRY = auto()
3317        HLLSKETCH = auto()
3318        HSTORE = auto()
3319        IMAGE = auto()
3320        INET = auto()
3321        INT = auto()
3322        INT128 = auto()
3323        INT256 = auto()
3324        INTERVAL = auto()
3325        JSON = auto()
3326        JSONB = auto()
3327        LONGBLOB = auto()
3328        LONGTEXT = auto()
3329        MAP = auto()
3330        MEDIUMBLOB = auto()
3331        MEDIUMTEXT = auto()
3332        MONEY = auto()
3333        NCHAR = auto()
3334        NULL = auto()
3335        NULLABLE = auto()
3336        NVARCHAR = auto()
3337        OBJECT = auto()
3338        ROWVERSION = auto()
3339        SERIAL = auto()
3340        SET = auto()
3341        SMALLINT = auto()
3342        SMALLMONEY = auto()
3343        SMALLSERIAL = auto()
3344        STRUCT = auto()
3345        SUPER = auto()
3346        TEXT = auto()
3347        TIME = auto()
3348        TIMESTAMP = auto()
3349        TIMESTAMPTZ = auto()
3350        TIMESTAMPLTZ = auto()
3351        TINYINT = auto()
3352        UBIGINT = auto()
3353        UINT = auto()
3354        USMALLINT = auto()
3355        UTINYINT = auto()
3356        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3357        UINT128 = auto()
3358        UINT256 = auto()
3359        UNIQUEIDENTIFIER = auto()
3360        USERDEFINED = "USER-DEFINED"
3361        UUID = auto()
3362        VARBINARY = auto()
3363        VARCHAR = auto()
3364        VARIANT = auto()
3365        XML = auto()

An enumeration.

ARRAY = <Type.ARRAY: 'ARRAY'>
BIGDECIMAL = <Type.BIGDECIMAL: 'BIGDECIMAL'>
BIGINT = <Type.BIGINT: 'BIGINT'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
BINARY = <Type.BINARY: 'BINARY'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
CHAR = <Type.CHAR: 'CHAR'>
DATE = <Type.DATE: 'DATE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
ENUM = <Type.ENUM: 'ENUM'>
INT4RANGE = <Type.INT4RANGE: 'INT4RANGE'>
INT4MULTIRANGE = <Type.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT8RANGE = <Type.INT8RANGE: 'INT8RANGE'>
INT8MULTIRANGE = <Type.INT8MULTIRANGE: 'INT8MULTIRANGE'>
NUMRANGE = <Type.NUMRANGE: 'NUMRANGE'>
NUMMULTIRANGE = <Type.NUMMULTIRANGE: 'NUMMULTIRANGE'>
TSRANGE = <Type.TSRANGE: 'TSRANGE'>
TSMULTIRANGE = <Type.TSMULTIRANGE: 'TSMULTIRANGE'>
TSTZRANGE = <Type.TSTZRANGE: 'TSTZRANGE'>
TSTZMULTIRANGE = <Type.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
DATERANGE = <Type.DATERANGE: 'DATERANGE'>
DATEMULTIRANGE = <Type.DATEMULTIRANGE: 'DATEMULTIRANGE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
FLOAT = <Type.FLOAT: 'FLOAT'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
IMAGE = <Type.IMAGE: 'IMAGE'>
INET = <Type.INET: 'INET'>
INT = <Type.INT: 'INT'>
INT128 = <Type.INT128: 'INT128'>
INT256 = <Type.INT256: 'INT256'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MAP = <Type.MAP: 'MAP'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
MONEY = <Type.MONEY: 'MONEY'>
NCHAR = <Type.NCHAR: 'NCHAR'>
NULL = <Type.NULL: 'NULL'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
OBJECT = <Type.OBJECT: 'OBJECT'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SET = <Type.SET: 'SET'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
STRUCT = <Type.STRUCT: 'STRUCT'>
SUPER = <Type.SUPER: 'SUPER'>
TEXT = <Type.TEXT: 'TEXT'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
UINT = <Type.UINT: 'UINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
UINT128 = <Type.UINT128: 'UINT128'>
UINT256 = <Type.UINT256: 'UINT256'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
USERDEFINED = <Type.USERDEFINED: 'USER-DEFINED'>
UUID = <Type.UUID: 'UUID'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
VARIANT = <Type.VARIANT: 'VARIANT'>
XML = <Type.XML: 'XML'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
3432class PseudoType(Expression):
3433    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3437class SubqueryPredicate(Predicate):
3438    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3441class All(SubqueryPredicate):
3442    pass
key = 'all'
class Any(SubqueryPredicate):
3445class Any(SubqueryPredicate):
3446    pass
key = 'any'
class Exists(SubqueryPredicate):
3449class Exists(SubqueryPredicate):
3450    pass
key = 'exists'
class Command(Expression):
3455class Command(Expression):
3456    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3459class Transaction(Expression):
3460    arg_types = {"this": False, "modes": False}
arg_types = {'this': False, 'modes': False}
key = 'transaction'
class Commit(Expression):
3463class Commit(Expression):
3464    arg_types = {"chain": False}
arg_types = {'chain': False}
key = 'commit'
class Rollback(Expression):
3467class Rollback(Expression):
3468    arg_types = {"savepoint": False}
arg_types = {'savepoint': False}
key = 'rollback'
class AlterTable(Expression):
3471class AlterTable(Expression):
3472    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3475class AddConstraint(Expression):
3476    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3479class DropPartition(Expression):
3480    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3484class Binary(Condition):
3485    arg_types = {"this": True, "expression": True}
3486
3487    @property
3488    def left(self):
3489        return self.this
3490
3491    @property
3492    def right(self):
3493        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3496class Add(Binary):
3497    pass
key = 'add'
class Connector(Binary):
3500class Connector(Binary):
3501    pass
key = 'connector'
class And(Connector):
3504class And(Connector):
3505    pass
key = 'and'
class Or(Connector):
3508class Or(Connector):
3509    pass
key = 'or'
class BitwiseAnd(Binary):
3512class BitwiseAnd(Binary):
3513    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3516class BitwiseLeftShift(Binary):
3517    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3520class BitwiseOr(Binary):
3521    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3524class BitwiseRightShift(Binary):
3525    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3528class BitwiseXor(Binary):
3529    pass
key = 'bitwisexor'
class Div(Binary):
3532class Div(Binary):
3533    pass
key = 'div'
class Overlaps(Binary):
3536class Overlaps(Binary):
3537    pass
key = 'overlaps'
class Dot(Binary):
3540class Dot(Binary):
3541    @property
3542    def name(self) -> str:
3543        return self.expression.name
3544
3545    @property
3546    def output_name(self) -> str:
3547        return self.name
3548
3549    @classmethod
3550    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3551        """Build a Dot object with a sequence of expressions."""
3552        if len(expressions) < 2:
3553            raise ValueError(f"Dot requires >= 2 expressions.")
3554
3555        a, b, *expressions = expressions
3556        dot = Dot(this=a, expression=b)
3557
3558        for expression in expressions:
3559            dot = Dot(this=dot, expression=expression)
3560
3561        return dot
name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3549    @classmethod
3550    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3551        """Build a Dot object with a sequence of expressions."""
3552        if len(expressions) < 2:
3553            raise ValueError(f"Dot requires >= 2 expressions.")
3554
3555        a, b, *expressions = expressions
3556        dot = Dot(this=a, expression=b)
3557
3558        for expression in expressions:
3559            dot = Dot(this=dot, expression=expression)
3560
3561        return dot

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3564class DPipe(Binary):
3565    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3568class SafeDPipe(DPipe):
3569    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3572class EQ(Binary, Predicate):
3573    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3576class NullSafeEQ(Binary, Predicate):
3577    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3580class NullSafeNEQ(Binary, Predicate):
3581    pass
key = 'nullsafeneq'
class Distance(Binary):
3584class Distance(Binary):
3585    pass
key = 'distance'
class Escape(Binary):
3588class Escape(Binary):
3589    pass
key = 'escape'
class Glob(Binary, Predicate):
3592class Glob(Binary, Predicate):
3593    pass
key = 'glob'
class GT(Binary, Predicate):
3596class GT(Binary, Predicate):
3597    pass
key = 'gt'
class GTE(Binary, Predicate):
3600class GTE(Binary, Predicate):
3601    pass
key = 'gte'
class ILike(Binary, Predicate):
3604class ILike(Binary, Predicate):
3605    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3608class ILikeAny(Binary, Predicate):
3609    pass
key = 'ilikeany'
class IntDiv(Binary):
3612class IntDiv(Binary):
3613    pass
key = 'intdiv'
class Is(Binary, Predicate):
3616class Is(Binary, Predicate):
3617    pass
key = 'is'
class Kwarg(Binary):
3620class Kwarg(Binary):
3621    """Kwarg in special functions like func(kwarg => y)."""

Kwarg in special functions like func(kwarg => y).

key = 'kwarg'
class Like(Binary, Predicate):
3624class Like(Binary, Predicate):
3625    pass
key = 'like'
class LikeAny(Binary, Predicate):
3628class LikeAny(Binary, Predicate):
3629    pass
key = 'likeany'
class LT(Binary, Predicate):
3632class LT(Binary, Predicate):
3633    pass
key = 'lt'
class LTE(Binary, Predicate):
3636class LTE(Binary, Predicate):
3637    pass
key = 'lte'
class Mod(Binary):
3640class Mod(Binary):
3641    pass
key = 'mod'
class Mul(Binary):
3644class Mul(Binary):
3645    pass
key = 'mul'
class NEQ(Binary, Predicate):
3648class NEQ(Binary, Predicate):
3649    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3652class SimilarTo(Binary, Predicate):
3653    pass
key = 'similarto'
class Slice(Binary):
3656class Slice(Binary):
3657    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3660class Sub(Binary):
3661    pass
key = 'sub'
class ArrayOverlaps(Binary):
3664class ArrayOverlaps(Binary):
3665    pass
key = 'arrayoverlaps'
class Unary(Condition):
3670class Unary(Condition):
3671    pass
key = 'unary'
class BitwiseNot(Unary):
3674class BitwiseNot(Unary):
3675    pass
key = 'bitwisenot'
class Not(Unary):
3678class Not(Unary):
3679    pass
key = 'not'
class Paren(Unary):
3682class Paren(Unary):
3683    arg_types = {"this": True, "with": False}
3684
3685    @property
3686    def output_name(self) -> str:
3687        return self.this.name
arg_types = {'this': True, 'with': False}
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'paren'
class Neg(Unary):
3690class Neg(Unary):
3691    pass
key = 'neg'
class Alias(Expression):
3694class Alias(Expression):
3695    arg_types = {"this": True, "alias": False}
3696
3697    @property
3698    def output_name(self) -> str:
3699        return self.alias
arg_types = {'this': True, 'alias': False}
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'alias'
class Aliases(Expression):
3702class Aliases(Expression):
3703    arg_types = {"this": True, "expressions": True}
3704
3705    @property
3706    def aliases(self):
3707        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3710class AtTimeZone(Expression):
3711    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3714class Between(Predicate):
3715    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3718class Bracket(Condition):
3719    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3722class SafeBracket(Bracket):
3723    """Represents array lookup where OOB index yields NULL instead of causing a failure."""

Represents array lookup where OOB index yields NULL instead of causing a failure.

key = 'safebracket'
class Distinct(Expression):
3726class Distinct(Expression):
3727    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3730class In(Predicate):
3731    arg_types = {
3732        "this": True,
3733        "expressions": False,
3734        "query": False,
3735        "unnest": False,
3736        "field": False,
3737        "is_global": False,
3738    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3741class TimeUnit(Expression):
3742    """Automatically converts unit arg into a var."""
3743
3744    arg_types = {"unit": False}
3745
3746    def __init__(self, **args):
3747        unit = args.get("unit")
3748        if isinstance(unit, (Column, Literal)):
3749            args["unit"] = Var(this=unit.name)
3750        elif isinstance(unit, Week):
3751            unit.set("this", Var(this=unit.this.name))
3752
3753        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3746    def __init__(self, **args):
3747        unit = args.get("unit")
3748        if isinstance(unit, (Column, Literal)):
3749            args["unit"] = Var(this=unit.name)
3750        elif isinstance(unit, Week):
3751            unit.set("this", Var(this=unit.this.name))
3752
3753        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
3756class Interval(TimeUnit):
3757    arg_types = {"this": False, "unit": False}
3758
3759    @property
3760    def unit(self) -> t.Optional[Var]:
3761        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3764class IgnoreNulls(Expression):
3765    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3768class RespectNulls(Expression):
3769    pass
key = 'respectnulls'
class Func(Condition):
3773class Func(Condition):
3774    """
3775    The base class for all function expressions.
3776
3777    Attributes:
3778        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3779            treated as a variable length argument and the argument's value will be stored as a list.
3780        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3781            for this function expression. These values are used to map this node to a name during parsing
3782            as well as to provide the function's name during SQL string generation. By default the SQL
3783            name is set to the expression's class name transformed to snake case.
3784    """
3785
3786    is_var_len_args = False
3787
3788    @classmethod
3789    def from_arg_list(cls, args):
3790        if cls.is_var_len_args:
3791            all_arg_keys = list(cls.arg_types)
3792            # If this function supports variable length argument treat the last argument as such.
3793            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3794            num_non_var = len(non_var_len_arg_keys)
3795
3796            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3797            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3798        else:
3799            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3800
3801        return cls(**args_dict)
3802
3803    @classmethod
3804    def sql_names(cls):
3805        if cls is Func:
3806            raise NotImplementedError(
3807                "SQL name is only supported by concrete function implementations"
3808            )
3809        if "_sql_names" not in cls.__dict__:
3810            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3811        return cls._sql_names
3812
3813    @classmethod
3814    def sql_name(cls):
3815        return cls.sql_names()[0]
3816
3817    @classmethod
3818    def default_parser_mappings(cls):
3819        return {name: cls.from_arg_list for name in cls.sql_names()}

The base class for all function expressions.

Attributes:
  • is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
  • _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
is_var_len_args = False
@classmethod
def from_arg_list(cls, args):
3788    @classmethod
3789    def from_arg_list(cls, args):
3790        if cls.is_var_len_args:
3791            all_arg_keys = list(cls.arg_types)
3792            # If this function supports variable length argument treat the last argument as such.
3793            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3794            num_non_var = len(non_var_len_arg_keys)
3795
3796            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3797            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3798        else:
3799            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3800
3801        return cls(**args_dict)
@classmethod
def sql_names(cls):
3803    @classmethod
3804    def sql_names(cls):
3805        if cls is Func:
3806            raise NotImplementedError(
3807                "SQL name is only supported by concrete function implementations"
3808            )
3809        if "_sql_names" not in cls.__dict__:
3810            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3811        return cls._sql_names
@classmethod
def sql_name(cls):
3813    @classmethod
3814    def sql_name(cls):
3815        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3817    @classmethod
3818    def default_parser_mappings(cls):
3819        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3822class AggFunc(Func):
3823    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3826class ParameterizedAgg(AggFunc):
3827    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3830class Abs(Func):
3831    pass
key = 'abs'
class Anonymous(Func):
3834class Anonymous(Func):
3835    arg_types = {"this": True, "expressions": False}
3836    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3841class Hll(AggFunc):
3842    arg_types = {"this": True, "expressions": False}
3843    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3846class ApproxDistinct(AggFunc):
3847    arg_types = {"this": True, "accuracy": False}
3848    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3851class Array(Func):
3852    arg_types = {"expressions": False}
3853    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3857class ToChar(Func):
3858    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3861class GenerateSeries(Func):
3862    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3865class ArrayAgg(AggFunc):
3866    pass
key = 'arrayagg'
class ArrayAll(Func):
3869class ArrayAll(Func):
3870    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3873class ArrayAny(Func):
3874    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3877class ArrayConcat(Func):
3878    arg_types = {"this": True, "expressions": False}
3879    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3882class ArrayContains(Binary, Func):
3883    pass
key = 'arraycontains'
class ArrayContained(Binary):
3886class ArrayContained(Binary):
3887    pass
key = 'arraycontained'
class ArrayFilter(Func):
3890class ArrayFilter(Func):
3891    arg_types = {"this": True, "expression": True}
3892    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
3895class ArrayJoin(Func):
3896    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
3899class ArraySize(Func):
3900    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
3903class ArraySort(Func):
3904    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
3907class ArraySum(Func):
3908    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
3911class ArrayUnionAgg(AggFunc):
3912    pass
key = 'arrayunionagg'
class Avg(AggFunc):
3915class Avg(AggFunc):
3916    pass
key = 'avg'
class AnyValue(AggFunc):
3919class AnyValue(AggFunc):
3920    pass
key = 'anyvalue'
class Case(Func):
3923class Case(Func):
3924    arg_types = {"this": False, "ifs": True, "default": False}
3925
3926    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3927        instance = _maybe_copy(self, copy)
3928        instance.append(
3929            "ifs",
3930            If(
3931                this=maybe_parse(condition, copy=copy, **opts),
3932                true=maybe_parse(then, copy=copy, **opts),
3933            ),
3934        )
3935        return instance
3936
3937    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3938        instance = _maybe_copy(self, copy)
3939        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3940        return instance
arg_types = {'this': False, 'ifs': True, 'default': False}
def when( self, condition: Union[str, sqlglot.expressions.Expression], then: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3926    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3927        instance = _maybe_copy(self, copy)
3928        instance.append(
3929            "ifs",
3930            If(
3931                this=maybe_parse(condition, copy=copy, **opts),
3932                true=maybe_parse(then, copy=copy, **opts),
3933            ),
3934        )
3935        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3937    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3938        instance = _maybe_copy(self, copy)
3939        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3940        return instance
key = 'case'
class Cast(Func):
3943class Cast(Func):
3944    arg_types = {"this": True, "to": True}
3945
3946    @property
3947    def name(self) -> str:
3948        return self.this.name
3949
3950    @property
3951    def to(self) -> DataType:
3952        return self.args["to"]
3953
3954    @property
3955    def output_name(self) -> str:
3956        return self.name
3957
3958    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3959        return self.to.is_type(*dtypes)
arg_types = {'this': True, 'to': True}
name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3958    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3959        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
3962class CastToStrType(Func):
3963    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
3966class Collate(Binary):
3967    pass
key = 'collate'
class TryCast(Cast):
3970class TryCast(Cast):
3971    pass
key = 'trycast'
class Ceil(Func):
3974class Ceil(Func):
3975    arg_types = {"this": True, "decimals": False}
3976    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
3979class Coalesce(Func):
3980    arg_types = {"this": True, "expressions": False}
3981    is_var_len_args = True
3982    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
3985class Concat(Func):
3986    arg_types = {"expressions": True}
3987    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
3990class SafeConcat(Concat):
3991    pass
key = 'safeconcat'
class ConcatWs(Concat):
3994class ConcatWs(Concat):
3995    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
3998class Count(AggFunc):
3999    arg_types = {"this": False, "expressions": False}
4000    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4003class CountIf(AggFunc):
4004    pass
key = 'countif'
class CurrentDate(Func):
4007class CurrentDate(Func):
4008    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4011class CurrentDatetime(Func):
4012    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4015class CurrentTime(Func):
4016    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4019class CurrentTimestamp(Func):
4020    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4023class CurrentUser(Func):
4024    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4027class DateAdd(Func, TimeUnit):
4028    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4031class DateSub(Func, TimeUnit):
4032    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4035class DateDiff(Func, TimeUnit):
4036    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4037    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4040class DateTrunc(Func):
4041    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4044class DatetimeAdd(Func, TimeUnit):
4045    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4048class DatetimeSub(Func, TimeUnit):
4049    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4052class DatetimeDiff(Func, TimeUnit):
4053    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4056class DatetimeTrunc(Func, TimeUnit):
4057    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4060class DayOfWeek(Func):
4061    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4064class DayOfMonth(Func):
4065    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4068class DayOfYear(Func):
4069    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4072class WeekOfYear(Func):
4073    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class LastDateOfMonth(Func):
4076class LastDateOfMonth(Func):
4077    pass
key = 'lastdateofmonth'
class Extract(Func):
4080class Extract(Func):
4081    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4084class TimestampAdd(Func, TimeUnit):
4085    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4088class TimestampSub(Func, TimeUnit):
4089    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4092class TimestampDiff(Func, TimeUnit):
4093    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4096class TimestampTrunc(Func, TimeUnit):
4097    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4100class TimeAdd(Func, TimeUnit):
4101    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4104class TimeSub(Func, TimeUnit):
4105    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4108class TimeDiff(Func, TimeUnit):
4109    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4112class TimeTrunc(Func, TimeUnit):
4113    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4116class DateFromParts(Func):
4117    _sql_names = ["DATEFROMPARTS"]
4118    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4121class DateStrToDate(Func):
4122    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4125class DateToDateStr(Func):
4126    pass
key = 'datetodatestr'
class DateToDi(Func):
4129class DateToDi(Func):
4130    pass
key = 'datetodi'
class Date(Func):
4133class Date(Func):
4134    arg_types = {"expressions": True}
4135    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'date'
class Day(Func):
4138class Day(Func):
4139    pass
key = 'day'
class Decode(Func):
4142class Decode(Func):
4143    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4146class DiToDate(Func):
4147    pass
key = 'ditodate'
class Encode(Func):
4150class Encode(Func):
4151    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4154class Exp(Func):
4155    pass
key = 'exp'
class Explode(Func):
4158class Explode(Func):
4159    pass
key = 'explode'
class Floor(Func):
4162class Floor(Func):
4163    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4166class FromBase64(Func):
4167    pass
key = 'frombase64'
class ToBase64(Func):
4170class ToBase64(Func):
4171    pass
key = 'tobase64'
class Greatest(Func):
4174class Greatest(Func):
4175    arg_types = {"this": True, "expressions": False}
4176    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4179class GroupConcat(Func):
4180    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4183class Hex(Func):
4184    pass
key = 'hex'
class If(Func):
4187class If(Func):
4188    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4191class Initcap(Func):
4192    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class JSONKeyValue(Expression):
4195class JSONKeyValue(Expression):
4196    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4199class JSONObject(Func):
4200    arg_types = {
4201        "expressions": False,
4202        "null_handling": False,
4203        "unique_keys": False,
4204        "return_type": False,
4205        "format_json": False,
4206        "encoding": False,
4207    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4210class OpenJSONColumnDef(Expression):
4211    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
arg_types = {'this': True, 'kind': True, 'path': False, 'as_json': False}
key = 'openjsoncolumndef'
class OpenJSON(Func):
4214class OpenJSON(Func):
4215    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4218class JSONBContains(Binary):
4219    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4222class JSONExtract(Binary, Func):
4223    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4226class JSONExtractScalar(JSONExtract):
4227    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4230class JSONBExtract(JSONExtract):
4231    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4234class JSONBExtractScalar(JSONExtract):
4235    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4238class JSONFormat(Func):
4239    arg_types = {"this": False, "options": False}
4240    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class Least(Func):
4243class Least(Func):
4244    arg_types = {"expressions": False}
4245    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4248class Left(Func):
4249    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4256class Length(Func):
4257    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4260class Levenshtein(Func):
4261    arg_types = {
4262        "this": True,
4263        "expression": False,
4264        "ins_cost": False,
4265        "del_cost": False,
4266        "sub_cost": False,
4267    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4270class Ln(Func):
4271    pass
key = 'ln'
class Log(Func):
4274class Log(Func):
4275    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4278class Log2(Func):
4279    pass
key = 'log2'
class Log10(Func):
4282class Log10(Func):
4283    pass
key = 'log10'
class LogicalOr(AggFunc):
4286class LogicalOr(AggFunc):
4287    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4290class LogicalAnd(AggFunc):
4291    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4294class Lower(Func):
4295    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4298class Map(Func):
4299    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4302class MapFromEntries(Func):
4303    pass
key = 'mapfromentries'
class StarMap(Func):
4306class StarMap(Func):
4307    pass
key = 'starmap'
class VarMap(Func):
4310class VarMap(Func):
4311    arg_types = {"keys": True, "values": True}
4312    is_var_len_args = True
4313
4314    @property
4315    def keys(self) -> t.List[Expression]:
4316        return self.args["keys"].expressions
4317
4318    @property
4319    def values(self) -> t.List[Expression]:
4320        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4324class MatchAgainst(Func):
4325    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4328class Max(AggFunc):
4329    arg_types = {"this": True, "expressions": False}
4330    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4333class MD5(Func):
4334    _sql_names = ["MD5"]
key = 'md5'
class Min(AggFunc):
4337class Min(AggFunc):
4338    arg_types = {"this": True, "expressions": False}
4339    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4342class Month(Func):
4343    pass
key = 'month'
class Nvl2(Func):
4346class Nvl2(Func):
4347    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4350class Posexplode(Func):
4351    pass
key = 'posexplode'
class Pow(Binary, Func):
4354class Pow(Binary, Func):
4355    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4358class PercentileCont(AggFunc):
4359    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4362class PercentileDisc(AggFunc):
4363    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4366class Quantile(AggFunc):
4367    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4370class ApproxQuantile(Quantile):
4371    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
arg_types = {'this': True, 'quantile': True, 'accuracy': False, 'weight': False}
key = 'approxquantile'
class RangeN(Func):
4374class RangeN(Func):
4375    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4378class ReadCSV(Func):
4379    _sql_names = ["READ_CSV"]
4380    is_var_len_args = True
4381    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4384class Reduce(Func):
4385    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
arg_types = {'this': True, 'initial': True, 'merge': True, 'finish': False}
key = 'reduce'
class RegexpExtract(Func):
4388class RegexpExtract(Func):
4389    arg_types = {
4390        "this": True,
4391        "expression": True,
4392        "position": False,
4393        "occurrence": False,
4394        "group": False,
4395    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'group': False}
key = 'regexpextract'
class RegexpLike(Func):
4398class RegexpLike(Func):
4399    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4402class RegexpILike(Func):
4403    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4408class RegexpSplit(Func):
4409    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4412class Repeat(Func):
4413    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4416class Round(Func):
4417    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4420class RowNumber(Func):
4421    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4424class SafeDivide(Func):
4425    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4428class SetAgg(AggFunc):
4429    pass
key = 'setagg'
class SHA(Func):
4432class SHA(Func):
4433    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4436class SHA2(Func):
4437    _sql_names = ["SHA2"]
4438    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4441class SortArray(Func):
4442    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4445class Split(Func):
4446    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4451class Substring(Func):
4452    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4455class StandardHash(Func):
4456    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StrPosition(Func):
4459class StrPosition(Func):
4460    arg_types = {
4461        "this": True,
4462        "substr": True,
4463        "position": False,
4464        "instance": False,
4465    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4468class StrToDate(Func):
4469    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4472class StrToTime(Func):
4473    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtotime'
class StrToUnix(Func):
4478class StrToUnix(Func):
4479    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4482class NumberToStr(Func):
4483    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4486class FromBase(Func):
4487    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4490class Struct(Func):
4491    arg_types = {"expressions": True}
4492    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4495class StructExtract(Func):
4496    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4499class Sum(AggFunc):
4500    pass
key = 'sum'
class Sqrt(Func):
4503class Sqrt(Func):
4504    pass
key = 'sqrt'
class Stddev(AggFunc):
4507class Stddev(AggFunc):
4508    pass
key = 'stddev'
class StddevPop(AggFunc):
4511class StddevPop(AggFunc):
4512    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4515class StddevSamp(AggFunc):
4516    pass
key = 'stddevsamp'
class TimeToStr(Func):
4519class TimeToStr(Func):
4520    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4523class TimeToTimeStr(Func):
4524    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4527class TimeToUnix(Func):
4528    pass
key = 'timetounix'
class TimeStrToDate(Func):
4531class TimeStrToDate(Func):
4532    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4535class TimeStrToTime(Func):
4536    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4539class TimeStrToUnix(Func):
4540    pass
key = 'timestrtounix'
class Trim(Func):
4543class Trim(Func):
4544    arg_types = {
4545        "this": True,
4546        "expression": False,
4547        "position": False,
4548        "collation": False,
4549    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4552class TsOrDsAdd(Func, TimeUnit):
4553    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4556class TsOrDsToDateStr(Func):
4557    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4560class TsOrDsToDate(Func):
4561    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4564class TsOrDiToDi(Func):
4565    pass
key = 'tsorditodi'
class Unhex(Func):
4568class Unhex(Func):
4569    pass
key = 'unhex'
class UnixToStr(Func):
4572class UnixToStr(Func):
4573    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4578class UnixToTime(Func):
4579    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4580
4581    SECONDS = Literal.string("seconds")
4582    MILLIS = Literal.string("millis")
4583    MICROS = Literal.string("micros")
arg_types = {'this': True, 'scale': False, 'zone': False, 'hours': False, 'minutes': False}
SECONDS = (LITERAL this: seconds, is_string: True)
MILLIS = (LITERAL this: millis, is_string: True)
MICROS = (LITERAL this: micros, is_string: True)
key = 'unixtotime'
class UnixToTimeStr(Func):
4586class UnixToTimeStr(Func):
4587    pass
key = 'unixtotimestr'
class Upper(Func):
4590class Upper(Func):
4591    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4594class Variance(AggFunc):
4595    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4598class VariancePop(AggFunc):
4599    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4602class Week(Func):
4603    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4606class XMLTable(Func):
4607    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
arg_types = {'this': True, 'passing': False, 'columns': False, 'by_ref': False}
key = 'xmltable'
class Year(Func):
4610class Year(Func):
4611    pass
key = 'year'
class Use(Expression):
4614class Use(Expression):
4615    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4618class Merge(Expression):
4619    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
arg_types = {'this': True, 'using': True, 'on': True, 'expressions': True}
key = 'merge'
class When(Func):
4622class When(Func):
4623    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
arg_types = {'matched': True, 'source': False, 'condition': False, 'then': True}
key = 'when'
class NextValueFor(Func):
4628class NextValueFor(Func):
4629    arg_types = {"this": True, "order": False}
arg_types = {'this': True, 'order': False}
key = 'nextvaluefor'
ALL_FUNCTIONS = [<class 'sqlglot.expressions.Abs'>, <class 'sqlglot.expressions.AnyValue'>, <class 'sqlglot.expressions.ApproxDistinct'>, <class 'sqlglot.expressions.ApproxQuantile'>, <class 'sqlglot.expressions.Array'>, <class 'sqlglot.expressions.ArrayAgg'>, <class 'sqlglot.expressions.ArrayAll'>, <class 'sqlglot.expressions.ArrayAny'>, <class 'sqlglot.expressions.ArrayConcat'>, <class 'sqlglot.expressions.ArrayContains'>, <class 'sqlglot.expressions.ArrayFilter'>, <class 'sqlglot.expressions.ArrayJoin'>, <class 'sqlglot.expressions.ArraySize'>, <class 'sqlglot.expressions.ArraySort'>, <class 'sqlglot.expressions.ArraySum'>, <class 'sqlglot.expressions.ArrayUnionAgg'>, <class 'sqlglot.expressions.Avg'>, <class 'sqlglot.expressions.Case'>, <class 'sqlglot.expressions.Cast'>, <class 'sqlglot.expressions.CastToStrType'>, <class 'sqlglot.expressions.Ceil'>, <class 'sqlglot.expressions.Coalesce'>, <class 'sqlglot.expressions.Concat'>, <class 'sqlglot.expressions.ConcatWs'>, <class 'sqlglot.expressions.Count'>, <class 'sqlglot.expressions.CountIf'>, <class 'sqlglot.expressions.CurrentDate'>, <class 'sqlglot.expressions.CurrentDatetime'>, <class 'sqlglot.expressions.CurrentTime'>, <class 'sqlglot.expressions.CurrentTimestamp'>, <class 'sqlglot.expressions.CurrentUser'>, <class 'sqlglot.expressions.Date'>, <class 'sqlglot.expressions.DateAdd'>, <class 'sqlglot.expressions.DateDiff'>, <class 'sqlglot.expressions.DateFromParts'>, <class 'sqlglot.expressions.DateStrToDate'>, <class 'sqlglot.expressions.DateSub'>, <class 'sqlglot.expressions.DateToDateStr'>, <class 'sqlglot.expressions.DateToDi'>, <class 'sqlglot.expressions.DateTrunc'>, <class 'sqlglot.expressions.DatetimeAdd'>, <class 'sqlglot.expressions.DatetimeDiff'>, <class 'sqlglot.expressions.DatetimeSub'>, <class 'sqlglot.expressions.DatetimeTrunc'>, <class 'sqlglot.expressions.Day'>, <class 'sqlglot.expressions.DayOfMonth'>, <class 'sqlglot.expressions.DayOfWeek'>, <class 'sqlglot.expressions.DayOfYear'>, <class 'sqlglot.expressions.Decode'>, <class 'sqlglot.expressions.DiToDate'>, <class 'sqlglot.expressions.Encode'>, <class 'sqlglot.expressions.Exp'>, <class 'sqlglot.expressions.Explode'>, <class 'sqlglot.expressions.Extract'>, <class 'sqlglot.expressions.Floor'>, <class 'sqlglot.expressions.FromBase'>, <class 'sqlglot.expressions.FromBase64'>, <class 'sqlglot.expressions.GenerateSeries'>, <class 'sqlglot.expressions.Greatest'>, <class 'sqlglot.expressions.GroupConcat'>, <class 'sqlglot.expressions.Hex'>, <class 'sqlglot.expressions.Hll'>, <class 'sqlglot.expressions.If'>, <class 'sqlglot.expressions.Initcap'>, <class 'sqlglot.expressions.JSONBExtract'>, <class 'sqlglot.expressions.JSONBExtractScalar'>, <class 'sqlglot.expressions.JSONExtract'>, <class 'sqlglot.expressions.JSONExtractScalar'>, <class 'sqlglot.expressions.JSONFormat'>, <class 'sqlglot.expressions.JSONObject'>, <class 'sqlglot.expressions.LastDateOfMonth'>, <class 'sqlglot.expressions.Least'>, <class 'sqlglot.expressions.Left'>, <class 'sqlglot.expressions.Length'>, <class 'sqlglot.expressions.Levenshtein'>, <class 'sqlglot.expressions.Ln'>, <class 'sqlglot.expressions.Log'>, <class 'sqlglot.expressions.Log10'>, <class 'sqlglot.expressions.Log2'>, <class 'sqlglot.expressions.LogicalAnd'>, <class 'sqlglot.expressions.LogicalOr'>, <class 'sqlglot.expressions.Lower'>, <class 'sqlglot.expressions.MD5'>, <class 'sqlglot.expressions.Map'>, <class 'sqlglot.expressions.MapFromEntries'>, <class 'sqlglot.expressions.MatchAgainst'>, <class 'sqlglot.expressions.Max'>, <class 'sqlglot.expressions.Min'>, <class 'sqlglot.expressions.Month'>, <class 'sqlglot.expressions.NextValueFor'>, <class 'sqlglot.expressions.NumberToStr'>, <class 'sqlglot.expressions.Nvl2'>, <class 'sqlglot.expressions.OpenJSON'>, <class 'sqlglot.expressions.ParameterizedAgg'>, <class 'sqlglot.expressions.PercentileCont'>, <class 'sqlglot.expressions.PercentileDisc'>, <class 'sqlglot.expressions.Posexplode'>, <class 'sqlglot.expressions.Pow'>, <class 'sqlglot.expressions.Quantile'>, <class 'sqlglot.expressions.RangeN'>, <class 'sqlglot.expressions.ReadCSV'>, <class 'sqlglot.expressions.Reduce'>, <class 'sqlglot.expressions.RegexpExtract'>, <class 'sqlglot.expressions.RegexpILike'>, <class 'sqlglot.expressions.RegexpLike'>, <class 'sqlglot.expressions.RegexpSplit'>, <class 'sqlglot.expressions.Repeat'>, <class 'sqlglot.expressions.Right'>, <class 'sqlglot.expressions.Round'>, <class 'sqlglot.expressions.RowNumber'>, <class 'sqlglot.expressions.SHA'>, <class 'sqlglot.expressions.SHA2'>, <class 'sqlglot.expressions.SafeConcat'>, <class 'sqlglot.expressions.SafeDivide'>, <class 'sqlglot.expressions.SetAgg'>, <class 'sqlglot.expressions.SortArray'>, <class 'sqlglot.expressions.Split'>, <class 'sqlglot.expressions.Sqrt'>, <class 'sqlglot.expressions.StandardHash'>, <class 'sqlglot.expressions.StarMap'>, <class 'sqlglot.expressions.Stddev'>, <class 'sqlglot.expressions.StddevPop'>, <class 'sqlglot.expressions.StddevSamp'>, <class 'sqlglot.expressions.StrPosition'>, <class 'sqlglot.expressions.StrToDate'>, <class 'sqlglot.expressions.StrToTime'>, <class 'sqlglot.expressions.StrToUnix'>, <class 'sqlglot.expressions.Struct'>, <class 'sqlglot.expressions.StructExtract'>, <class 'sqlglot.expressions.Substring'>, <class 'sqlglot.expressions.Sum'>, <class 'sqlglot.expressions.TimeAdd'>, <class 'sqlglot.expressions.TimeDiff'>, <class 'sqlglot.expressions.TimeStrToDate'>, <class 'sqlglot.expressions.TimeStrToTime'>, <class 'sqlglot.expressions.TimeStrToUnix'>, <class 'sqlglot.expressions.TimeSub'>, <class 'sqlglot.expressions.TimeToStr'>, <class 'sqlglot.expressions.TimeToTimeStr'>, <class 'sqlglot.expressions.TimeToUnix'>, <class 'sqlglot.expressions.TimeTrunc'>, <class 'sqlglot.expressions.TimestampAdd'>, <class 'sqlglot.expressions.TimestampDiff'>, <class 'sqlglot.expressions.TimestampSub'>, <class 'sqlglot.expressions.TimestampTrunc'>, <class 'sqlglot.expressions.ToBase64'>, <class 'sqlglot.expressions.ToChar'>, <class 'sqlglot.expressions.Trim'>, <class 'sqlglot.expressions.TryCast'>, <class 'sqlglot.expressions.TsOrDiToDi'>, <class 'sqlglot.expressions.TsOrDsAdd'>, <class 'sqlglot.expressions.TsOrDsToDate'>, <class 'sqlglot.expressions.TsOrDsToDateStr'>, <class 'sqlglot.expressions.Unhex'>, <class 'sqlglot.expressions.UnixToStr'>, <class 'sqlglot.expressions.UnixToTime'>, <class 'sqlglot.expressions.UnixToTimeStr'>, <class 'sqlglot.expressions.Upper'>, <class 'sqlglot.expressions.VarMap'>, <class 'sqlglot.expressions.Variance'>, <class 'sqlglot.expressions.VariancePop'>, <class 'sqlglot.expressions.Week'>, <class 'sqlglot.expressions.WeekOfYear'>, <class 'sqlglot.expressions.When'>, <class 'sqlglot.expressions.XMLTable'>, <class 'sqlglot.expressions.Year'>]
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
4666def maybe_parse(
4667    sql_or_expression: ExpOrStr,
4668    *,
4669    into: t.Optional[IntoType] = None,
4670    dialect: DialectType = None,
4671    prefix: t.Optional[str] = None,
4672    copy: bool = False,
4673    **opts,
4674) -> Expression:
4675    """Gracefully handle a possible string or expression.
4676
4677    Example:
4678        >>> maybe_parse("1")
4679        (LITERAL this: 1, is_string: False)
4680        >>> maybe_parse(to_identifier("x"))
4681        (IDENTIFIER this: x, quoted: False)
4682
4683    Args:
4684        sql_or_expression: the SQL code string or an expression
4685        into: the SQLGlot Expression to parse into
4686        dialect: the dialect used to parse the input expressions (in the case that an
4687            input expression is a SQL string).
4688        prefix: a string to prefix the sql with before it gets parsed
4689            (automatically includes a space)
4690        copy: whether or not to copy the expression.
4691        **opts: other options to use to parse the input expressions (again, in the case
4692            that an input expression is a SQL string).
4693
4694    Returns:
4695        Expression: the parsed or given expression.
4696    """
4697    if isinstance(sql_or_expression, Expression):
4698        if copy:
4699            return sql_or_expression.copy()
4700        return sql_or_expression
4701
4702    if sql_or_expression is None:
4703        raise ParseError(f"SQL cannot be None")
4704
4705    import sqlglot
4706
4707    sql = str(sql_or_expression)
4708    if prefix:
4709        sql = f"{prefix} {sql}"
4710
4711    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
(LITERAL this: 1, is_string: False)
>>> maybe_parse(to_identifier("x"))
(IDENTIFIER this: x, quoted: False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expression to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expression: the parsed or given expression.

def union( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Union:
4895def union(
4896    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4897) -> Union:
4898    """
4899    Initializes a syntax tree from one UNION expression.
4900
4901    Example:
4902        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4903        'SELECT * FROM foo UNION SELECT * FROM bla'
4904
4905    Args:
4906        left: the SQL code string corresponding to the left-hand side.
4907            If an `Expression` instance is passed, it will be used as-is.
4908        right: the SQL code string corresponding to the right-hand side.
4909            If an `Expression` instance is passed, it will be used as-is.
4910        distinct: set the DISTINCT flag if and only if this is true.
4911        dialect: the dialect used to parse the input expression.
4912        opts: other options to use to parse the input expressions.
4913
4914    Returns:
4915        The new Union instance.
4916    """
4917    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4918    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4919
4920    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Union instance.

def intersect( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Intersect:
4923def intersect(
4924    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4925) -> Intersect:
4926    """
4927    Initializes a syntax tree from one INTERSECT expression.
4928
4929    Example:
4930        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4931        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4932
4933    Args:
4934        left: the SQL code string corresponding to the left-hand side.
4935            If an `Expression` instance is passed, it will be used as-is.
4936        right: the SQL code string corresponding to the right-hand side.
4937            If an `Expression` instance is passed, it will be used as-is.
4938        distinct: set the DISTINCT flag if and only if this is true.
4939        dialect: the dialect used to parse the input expression.
4940        opts: other options to use to parse the input expressions.
4941
4942    Returns:
4943        The new Intersect instance.
4944    """
4945    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4946    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4947
4948    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Intersect instance.

def except_( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Except:
4951def except_(
4952    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4953) -> Except:
4954    """
4955    Initializes a syntax tree from one EXCEPT expression.
4956
4957    Example:
4958        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4959        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4960
4961    Args:
4962        left: the SQL code string corresponding to the left-hand side.
4963            If an `Expression` instance is passed, it will be used as-is.
4964        right: the SQL code string corresponding to the right-hand side.
4965            If an `Expression` instance is passed, it will be used as-is.
4966        distinct: set the DISTINCT flag if and only if this is true.
4967        dialect: the dialect used to parse the input expression.
4968        opts: other options to use to parse the input expressions.
4969
4970    Returns:
4971        The new Except instance.
4972    """
4973    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4974    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4975
4976    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Except instance.

def select( *expressions: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4979def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4980    """
4981    Initializes a syntax tree from one or multiple SELECT expressions.
4982
4983    Example:
4984        >>> select("col1", "col2").from_("tbl").sql()
4985        'SELECT col1, col2 FROM tbl'
4986
4987    Args:
4988        *expressions: the SQL code string to parse as the expressions of a
4989            SELECT statement. If an Expression instance is passed, this is used as-is.
4990        dialect: the dialect used to parse the input expressions (in the case that an
4991            input expression is a SQL string).
4992        **opts: other options to use to parse the input expressions (again, in the case
4993            that an input expression is a SQL string).
4994
4995    Returns:
4996        Select: the syntax tree for the SELECT statement.
4997    """
4998    return Select().select(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from one or multiple SELECT expressions.

Example:
>>> select("col1", "col2").from_("tbl").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def from_( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
5001def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5002    """
5003    Initializes a syntax tree from a FROM expression.
5004
5005    Example:
5006        >>> from_("tbl").select("col1", "col2").sql()
5007        'SELECT col1, col2 FROM tbl'
5008
5009    Args:
5010        *expression: the SQL code string to parse as the FROM expressions of a
5011            SELECT statement. If an Expression instance is passed, this is used as-is.
5012        dialect: the dialect used to parse the input expression (in the case that the
5013            input expression is a SQL string).
5014        **opts: other options to use to parse the input expressions (again, in the case
5015            that the input expression is a SQL string).
5016
5017    Returns:
5018        Select: the syntax tree for the SELECT statement.
5019    """
5020    return Select().from_(expression, dialect=dialect, **opts)

Initializes a syntax tree from a FROM expression.

Example:
>>> from_("tbl").select("col1", "col2").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expression: the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def update( table: str | sqlglot.expressions.Table, properties: dict, where: Union[str, sqlglot.expressions.Expression, NoneType] = None, from_: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Update:
5023def update(
5024    table: str | Table,
5025    properties: dict,
5026    where: t.Optional[ExpOrStr] = None,
5027    from_: t.Optional[ExpOrStr] = None,
5028    dialect: DialectType = None,
5029    **opts,
5030) -> Update:
5031    """
5032    Creates an update statement.
5033
5034    Example:
5035        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5036        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5037
5038    Args:
5039        *properties: dictionary of properties to set which are
5040            auto converted to sql objects eg None -> NULL
5041        where: sql conditional parsed into a WHERE statement
5042        from_: sql statement parsed into a FROM statement
5043        dialect: the dialect used to parse the input expressions.
5044        **opts: other options to use to parse the input expressions.
5045
5046    Returns:
5047        Update: the syntax tree for the UPDATE statement.
5048    """
5049    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5050    update_expr.set(
5051        "expressions",
5052        [
5053            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5054            for k, v in properties.items()
5055        ],
5056    )
5057    if from_:
5058        update_expr.set(
5059            "from",
5060            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5061        )
5062    if isinstance(where, Condition):
5063        where = Where(this=where)
5064    if where:
5065        update_expr.set(
5066            "where",
5067            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5068        )
5069    return update_expr

Creates an update statement.

Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
"UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
  • *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
  • where: sql conditional parsed into a WHERE statement
  • from_: sql statement parsed into a FROM statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Update: the syntax tree for the UPDATE statement.

def delete( table: Union[str, sqlglot.expressions.Expression], where: Union[str, sqlglot.expressions.Expression, NoneType] = None, returning: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Delete:
5072def delete(
5073    table: ExpOrStr,
5074    where: t.Optional[ExpOrStr] = None,
5075    returning: t.Optional[ExpOrStr] = None,
5076    dialect: DialectType = None,
5077    **opts,
5078) -> Delete:
5079    """
5080    Builds a delete statement.
5081
5082    Example:
5083        >>> delete("my_table", where="id > 1").sql()
5084        'DELETE FROM my_table WHERE id > 1'
5085
5086    Args:
5087        where: sql conditional parsed into a WHERE statement
5088        returning: sql conditional parsed into a RETURNING statement
5089        dialect: the dialect used to parse the input expressions.
5090        **opts: other options to use to parse the input expressions.
5091
5092    Returns:
5093        Delete: the syntax tree for the DELETE statement.
5094    """
5095    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5096    if where:
5097        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5098    if returning:
5099        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5100    return delete_expr

Builds a delete statement.

Example:
>>> delete("my_table", where="id > 1").sql()
'DELETE FROM my_table WHERE id > 1'
Arguments:
  • where: sql conditional parsed into a WHERE statement
  • returning: sql conditional parsed into a RETURNING statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Delete: the syntax tree for the DELETE statement.

def insert( expression: Union[str, sqlglot.expressions.Expression], into: Union[str, sqlglot.expressions.Expression], columns: Optional[Sequence[Union[str, sqlglot.expressions.Expression]]] = None, overwrite: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Insert:
5103def insert(
5104    expression: ExpOrStr,
5105    into: ExpOrStr,
5106    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5107    overwrite: t.Optional[bool] = None,
5108    dialect: DialectType = None,
5109    copy: bool = True,
5110    **opts,
5111) -> Insert:
5112    """
5113    Builds an INSERT statement.
5114
5115    Example:
5116        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5117        'INSERT INTO tbl VALUES (1, 2, 3)'
5118
5119    Args:
5120        expression: the sql string or expression of the INSERT statement
5121        into: the tbl to insert data to.
5122        columns: optionally the table's column names.
5123        overwrite: whether to INSERT OVERWRITE or not.
5124        dialect: the dialect used to parse the input expressions.
5125        copy: whether or not to copy the expression.
5126        **opts: other options to use to parse the input expressions.
5127
5128    Returns:
5129        Insert: the syntax tree for the INSERT statement.
5130    """
5131    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5132    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5133
5134    if columns:
5135        this = _apply_list_builder(
5136            *columns,
5137            instance=Schema(this=this),
5138            arg="expressions",
5139            into=Identifier,
5140            copy=False,
5141            dialect=dialect,
5142            **opts,
5143        )
5144
5145    return Insert(this=this, expression=expr, overwrite=overwrite)

Builds an INSERT statement.

Example:
>>> insert("VALUES (1, 2, 3)", "tbl").sql()
'INSERT INTO tbl VALUES (1, 2, 3)'
Arguments:
  • expression: the sql string or expression of the INSERT statement
  • into: the tbl to insert data to.
  • columns: optionally the table's column names.
  • overwrite: whether to INSERT OVERWRITE or not.
  • dialect: the dialect used to parse the input expressions.
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Insert: the syntax tree for the INSERT statement.

def condition( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5148def condition(
5149    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5150) -> Condition:
5151    """
5152    Initialize a logical condition expression.
5153
5154    Example:
5155        >>> condition("x=1").sql()
5156        'x = 1'
5157
5158        This is helpful for composing larger logical syntax trees:
5159        >>> where = condition("x=1")
5160        >>> where = where.and_("y=1")
5161        >>> Select().from_("tbl").select("*").where(where).sql()
5162        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5163
5164    Args:
5165        *expression: the SQL code string to parse.
5166            If an Expression instance is passed, this is used as-is.
5167        dialect: the dialect used to parse the input expression (in the case that the
5168            input expression is a SQL string).
5169        copy: Whether or not to copy `expression` (only applies to expressions).
5170        **opts: other options to use to parse the input expressions (again, in the case
5171            that the input expression is a SQL string).
5172
5173    Returns:
5174        The new Condition instance
5175    """
5176    return maybe_parse(
5177        expression,
5178        into=Condition,
5179        dialect=dialect,
5180        copy=copy,
5181        **opts,
5182    )

Initialize a logical condition expression.

Example:
>>> condition("x=1").sql()
'x = 1'

This is helpful for composing larger logical syntax trees:

>>> where = condition("x=1")
>>> where = where.and_("y=1")
>>> Select().from_("tbl").select("*").where(where).sql()
'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
  • *expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • copy: Whether or not to copy expression (only applies to expressions).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

The new Condition instance

def and_( *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5185def and_(
5186    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5187) -> Condition:
5188    """
5189    Combine multiple conditions with an AND logical operator.
5190
5191    Example:
5192        >>> and_("x=1", and_("y=1", "z=1")).sql()
5193        'x = 1 AND (y = 1 AND z = 1)'
5194
5195    Args:
5196        *expressions: the SQL code strings to parse.
5197            If an Expression instance is passed, this is used as-is.
5198        dialect: the dialect used to parse the input expression.
5199        copy: whether or not to copy `expressions` (only applies to Expressions).
5200        **opts: other options to use to parse the input expressions.
5201
5202    Returns:
5203        And: the new condition
5204    """
5205    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts))

Combine multiple conditions with an AND logical operator.

Example:
>>> and_("x=1", and_("y=1", "z=1")).sql()
'x = 1 AND (y = 1 AND z = 1)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

And: the new condition

def or_( *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5208def or_(
5209    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5210) -> Condition:
5211    """
5212    Combine multiple conditions with an OR logical operator.
5213
5214    Example:
5215        >>> or_("x=1", or_("y=1", "z=1")).sql()
5216        'x = 1 OR (y = 1 OR z = 1)'
5217
5218    Args:
5219        *expressions: the SQL code strings to parse.
5220            If an Expression instance is passed, this is used as-is.
5221        dialect: the dialect used to parse the input expression.
5222        copy: whether or not to copy `expressions` (only applies to Expressions).
5223        **opts: other options to use to parse the input expressions.
5224
5225    Returns:
5226        Or: the new condition
5227    """
5228    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts))

Combine multiple conditions with an OR logical operator.

Example:
>>> or_("x=1", or_("y=1", "z=1")).sql()
'x = 1 OR (y = 1 OR z = 1)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

Or: the new condition

def not_( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Not:
5231def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5232    """
5233    Wrap a condition with a NOT operator.
5234
5235    Example:
5236        >>> not_("this_suit='black'").sql()
5237        "NOT this_suit = 'black'"
5238
5239    Args:
5240        expression: the SQL code string to parse.
5241            If an Expression instance is passed, this is used as-is.
5242        dialect: the dialect used to parse the input expression.
5243        copy: whether to copy the expression or not.
5244        **opts: other options to use to parse the input expressions.
5245
5246    Returns:
5247        The new condition.
5248    """
5249    this = condition(
5250        expression,
5251        dialect=dialect,
5252        copy=copy,
5253        **opts,
5254    )
5255    return Not(this=_wrap(this, Connector))

Wrap a condition with a NOT operator.

Example:
>>> not_("this_suit='black'").sql()
"NOT this_suit = 'black'"
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy the expression or not.
  • **opts: other options to use to parse the input expressions.
Returns:

The new condition.

def paren( expression: Union[str, sqlglot.expressions.Expression], copy: bool = True) -> sqlglot.expressions.Paren:
5258def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5259    """
5260    Wrap an expression in parentheses.
5261
5262    Example:
5263        >>> paren("5 + 3").sql()
5264        '(5 + 3)'
5265
5266    Args:
5267        expression: the SQL code string to parse.
5268            If an Expression instance is passed, this is used as-is.
5269        copy: whether to copy the expression or not.
5270
5271    Returns:
5272        The wrapped expression.
5273    """
5274    return Paren(this=maybe_parse(expression, copy=copy))

Wrap an expression in parentheses.

Example:
>>> paren("5 + 3").sql()
'(5 + 3)'
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • copy: whether to copy the expression or not.
Returns:

The wrapped expression.

SAFE_IDENTIFIER_RE = re.compile('^[_a-zA-Z][\\w]*$')
def to_identifier(name, quoted=None, copy=True):
5292def to_identifier(name, quoted=None, copy=True):
5293    """Builds an identifier.
5294
5295    Args:
5296        name: The name to turn into an identifier.
5297        quoted: Whether or not force quote the identifier.
5298        copy: Whether or not to copy a passed in Identefier node.
5299
5300    Returns:
5301        The identifier ast node.
5302    """
5303
5304    if name is None:
5305        return None
5306
5307    if isinstance(name, Identifier):
5308        identifier = _maybe_copy(name, copy)
5309    elif isinstance(name, str):
5310        identifier = Identifier(
5311            this=name,
5312            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5313        )
5314    else:
5315        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5316    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether or not force quote the identifier.
  • copy: Whether or not to copy a passed in Identefier node.
Returns:

The identifier ast node.

INTERVAL_STRING_RE = re.compile('\\s*([0-9]+)\\s*([a-zA-Z]+)\\s*')
def to_interval( interval: str | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
5322def to_interval(interval: str | Literal) -> Interval:
5323    """Builds an interval expression from a string like '1 day' or '5 months'."""
5324    if isinstance(interval, Literal):
5325        if not interval.is_string:
5326            raise ValueError("Invalid interval string.")
5327
5328        interval = interval.this
5329
5330    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5331
5332    if not interval_parts:
5333        raise ValueError("Invalid interval string.")
5334
5335    return Interval(
5336        this=Literal.string(interval_parts.group(1)),
5337        unit=Var(this=interval_parts.group(2)),
5338    )

Builds an interval expression from a string like '1 day' or '5 months'.

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> Optional[sqlglot.expressions.Table]:
5351def to_table(
5352    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5353) -> t.Optional[Table]:
5354    """
5355    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5356    If a table is passed in then that table is returned.
5357
5358    Args:
5359        sql_path: a `[catalog].[schema].[table]` string.
5360        dialect: the source dialect according to which the table name will be parsed.
5361        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5362
5363    Returns:
5364        A table expression.
5365    """
5366    if sql_path is None or isinstance(sql_path, Table):
5367        return sql_path
5368    if not isinstance(sql_path, str):
5369        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5370
5371    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5372    if table:
5373        for k, v in kwargs.items():
5374            table.set(k, v)
5375
5376    return table

Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional. If a table is passed in then that table is returned.

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
  • dialect: the source dialect according to which the table name will be parsed.
  • kwargs: the kwargs to instantiate the resulting Table expression with.
Returns:

A table expression.

def to_column( sql_path: str | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
5379def to_column(sql_path: str | Column, **kwargs) -> Column:
5380    """
5381    Create a column from a `[table].[column]` sql path. Schema is optional.
5382
5383    If a column is passed in then that column is returned.
5384
5385    Args:
5386        sql_path: `[table].[column]` string
5387    Returns:
5388        Table: A column expression
5389    """
5390    if sql_path is None or isinstance(sql_path, Column):
5391        return sql_path
5392    if not isinstance(sql_path, str):
5393        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5394    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore

Create a column from a [table].[column] sql path. Schema is optional.

If a column is passed in then that column is returned.

Arguments:
  • sql_path: [table].[column] string
Returns:

Table: A column expression

def alias_( expression: Union[str, sqlglot.expressions.Expression], alias: str | sqlglot.expressions.Identifier, table: Union[bool, Sequence[str | sqlglot.expressions.Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts):
5397def alias_(
5398    expression: ExpOrStr,
5399    alias: str | Identifier,
5400    table: bool | t.Sequence[str | Identifier] = False,
5401    quoted: t.Optional[bool] = None,
5402    dialect: DialectType = None,
5403    copy: bool = True,
5404    **opts,
5405):
5406    """Create an Alias expression.
5407
5408    Example:
5409        >>> alias_('foo', 'bar').sql()
5410        'foo AS bar'
5411
5412        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5413        '(SELECT 1, 2) AS bar(a, b)'
5414
5415    Args:
5416        expression: the SQL code strings to parse.
5417            If an Expression instance is passed, this is used as-is.
5418        alias: the alias name to use. If the name has
5419            special characters it is quoted.
5420        table: Whether or not to create a table alias, can also be a list of columns.
5421        quoted: whether or not to quote the alias
5422        dialect: the dialect used to parse the input expression.
5423        copy: Whether or not to copy the expression.
5424        **opts: other options to use to parse the input expressions.
5425
5426    Returns:
5427        Alias: the aliased expression
5428    """
5429    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5430    alias = to_identifier(alias, quoted=quoted)
5431
5432    if table:
5433        table_alias = TableAlias(this=alias)
5434        exp.set("alias", table_alias)
5435
5436        if not isinstance(table, bool):
5437            for column in table:
5438                table_alias.append("columns", to_identifier(column, quoted=quoted))
5439
5440        return exp
5441
5442    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5443    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5444    # for the complete Window expression.
5445    #
5446    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5447
5448    if "alias" in exp.arg_types and not isinstance(exp, Window):
5449        exp.set("alias", alias)
5450        return exp
5451    return Alias(this=exp, alias=alias)

Create an Alias expression.

Example:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
'(SELECT 1, 2) AS bar(a, b)'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use. If the name has special characters it is quoted.
  • table: Whether or not to create a table alias, can also be a list of columns.
  • quoted: whether or not to quote the alias
  • dialect: the dialect used to parse the input expression.
  • copy: Whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery( expression: Union[str, sqlglot.expressions.Expression], alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
5454def subquery(
5455    expression: ExpOrStr,
5456    alias: t.Optional[Identifier | str] = None,
5457    dialect: DialectType = None,
5458    **opts,
5459) -> Select:
5460    """
5461    Build a subquery expression.
5462
5463    Example:
5464        >>> subquery('select x from tbl', 'bar').select('x').sql()
5465        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5466
5467    Args:
5468        expression: the SQL code strings to parse.
5469            If an Expression instance is passed, this is used as-is.
5470        alias: the alias name to use.
5471        dialect: the dialect used to parse the input expression.
5472        **opts: other options to use to parse the input expressions.
5473
5474    Returns:
5475        A new Select instance with the subquery expression included.
5476    """
5477
5478    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5479    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

Example:
>>> subquery('select x from tbl', 'bar').select('x').sql()
'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use.
  • dialect: the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

A new Select instance with the subquery expression included.

def column( col: str | sqlglot.expressions.Identifier, table: Union[sqlglot.expressions.Identifier, str, NoneType] = None, db: Union[sqlglot.expressions.Identifier, str, NoneType] = None, catalog: Union[sqlglot.expressions.Identifier, str, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
5482def column(
5483    col: str | Identifier,
5484    table: t.Optional[str | Identifier] = None,
5485    db: t.Optional[str | Identifier] = None,
5486    catalog: t.Optional[str | Identifier] = None,
5487    quoted: t.Optional[bool] = None,
5488) -> Column:
5489    """
5490    Build a Column.
5491
5492    Args:
5493        col: Column name.
5494        table: Table name.
5495        db: Database name.
5496        catalog: Catalog name.
5497        quoted: Whether to force quotes on the column's identifiers.
5498
5499    Returns:
5500        The new Column instance.
5501    """
5502    return Column(
5503        this=to_identifier(col, quoted=quoted),
5504        table=to_identifier(table, quoted=quoted),
5505        db=to_identifier(db, quoted=quoted),
5506        catalog=to_identifier(catalog, quoted=quoted),
5507    )

Build a Column.

Arguments:
  • col: Column name.
  • table: Table name.
  • db: Database name.
  • catalog: Catalog name.
  • quoted: Whether to force quotes on the column's identifiers.
Returns:

The new Column instance.

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
5510def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5511    """Cast an expression to a data type.
5512
5513    Example:
5514        >>> cast('x + 1', 'int').sql()
5515        'CAST(x + 1 AS INT)'
5516
5517    Args:
5518        expression: The expression to cast.
5519        to: The datatype to cast to.
5520
5521    Returns:
5522        The new Cast instance.
5523    """
5524    expression = maybe_parse(expression, **opts)
5525    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

Example:
>>> cast('x + 1', 'int').sql()
'CAST(x + 1 AS INT)'
Arguments:
  • expression: The expression to cast.
  • to: The datatype to cast to.
Returns:

The new Cast instance.

def table_( table: sqlglot.expressions.Identifier | str, db: Union[sqlglot.expressions.Identifier, str, NoneType] = None, catalog: Union[sqlglot.expressions.Identifier, str, NoneType] = None, quoted: Optional[bool] = None, alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None) -> sqlglot.expressions.Table:
5528def table_(
5529    table: Identifier | str,
5530    db: t.Optional[Identifier | str] = None,
5531    catalog: t.Optional[Identifier | str] = None,
5532    quoted: t.Optional[bool] = None,
5533    alias: t.Optional[Identifier | str] = None,
5534) -> Table:
5535    """Build a Table.
5536
5537    Args:
5538        table: Table name.
5539        db: Database name.
5540        catalog: Catalog name.
5541        quote: Whether to force quotes on the table's identifiers.
5542        alias: Table's alias.
5543
5544    Returns:
5545        The new Table instance.
5546    """
5547    return Table(
5548        this=to_identifier(table, quoted=quoted),
5549        db=to_identifier(db, quoted=quoted),
5550        catalog=to_identifier(catalog, quoted=quoted),
5551        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5552    )

Build a Table.

Arguments:
  • table: Table name.
  • db: Database name.
  • catalog: Catalog name.
  • quote: Whether to force quotes on the table's identifiers.
  • alias: Table's alias.
Returns:

The new Table instance.

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, sqlglot.expressions.DataType], NoneType] = None) -> sqlglot.expressions.Values:
5555def values(
5556    values: t.Iterable[t.Tuple[t.Any, ...]],
5557    alias: t.Optional[str] = None,
5558    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5559) -> Values:
5560    """Build VALUES statement.
5561
5562    Example:
5563        >>> values([(1, '2')]).sql()
5564        "VALUES (1, '2')"
5565
5566    Args:
5567        values: values statements that will be converted to SQL
5568        alias: optional alias
5569        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5570         If either are provided then an alias is also required.
5571
5572    Returns:
5573        Values: the Values expression object
5574    """
5575    if columns and not alias:
5576        raise ValueError("Alias is required when providing columns")
5577
5578    return Values(
5579        expressions=[convert(tup) for tup in values],
5580        alias=(
5581            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5582            if columns
5583            else (TableAlias(this=to_identifier(alias)) if alias else None)
5584        ),
5585    )

Build VALUES statement.

Example:
>>> values([(1, '2')]).sql()
"VALUES (1, '2')"
Arguments:
  • values: values statements that will be converted to SQL
  • alias: optional alias
  • columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required.
Returns:

Values: the Values expression object

def var( name: Union[str, sqlglot.expressions.Expression, NoneType]) -> sqlglot.expressions.Var:
5588def var(name: t.Optional[ExpOrStr]) -> Var:
5589    """Build a SQL variable.
5590
5591    Example:
5592        >>> repr(var('x'))
5593        '(VAR this: x)'
5594
5595        >>> repr(var(column('x', table='y')))
5596        '(VAR this: x)'
5597
5598    Args:
5599        name: The name of the var or an expression who's name will become the var.
5600
5601    Returns:
5602        The new variable node.
5603    """
5604    if not name:
5605        raise ValueError("Cannot convert empty name into var.")
5606
5607    if isinstance(name, Expression):
5608        name = name.name
5609    return Var(this=name)

Build a SQL variable.

Example:
>>> repr(var('x'))
'(VAR this: x)'
>>> repr(var(column('x', table='y')))
'(VAR this: x)'
Arguments:
  • name: The name of the var or an expression who's name will become the var.
Returns:

The new variable node.

def rename_table( old_name: str | sqlglot.expressions.Table, new_name: str | sqlglot.expressions.Table) -> sqlglot.expressions.AlterTable:
5612def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5613    """Build ALTER TABLE... RENAME... expression
5614
5615    Args:
5616        old_name: The old name of the table
5617        new_name: The new name of the table
5618
5619    Returns:
5620        Alter table expression
5621    """
5622    old_table = to_table(old_name)
5623    new_table = to_table(new_name)
5624    return AlterTable(
5625        this=old_table,
5626        actions=[
5627            RenameTable(this=new_table),
5628        ],
5629    )

Build ALTER TABLE... RENAME... expression

Arguments:
  • old_name: The old name of the table
  • new_name: The new name of the table
Returns:

Alter table expression

def convert(value: Any, copy: bool = False) -> sqlglot.expressions.Expression:
5632def convert(value: t.Any, copy: bool = False) -> Expression:
5633    """Convert a python value into an expression object.
5634
5635    Raises an error if a conversion is not possible.
5636
5637    Args:
5638        value: A python object.
5639        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5640
5641    Returns:
5642        Expression: the equivalent expression object.
5643    """
5644    if isinstance(value, Expression):
5645        return _maybe_copy(value, copy)
5646    if isinstance(value, str):
5647        return Literal.string(value)
5648    if isinstance(value, bool):
5649        return Boolean(this=value)
5650    if value is None or (isinstance(value, float) and math.isnan(value)):
5651        return NULL
5652    if isinstance(value, numbers.Number):
5653        return Literal.number(value)
5654    if isinstance(value, datetime.datetime):
5655        datetime_literal = Literal.string(
5656            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5657        )
5658        return TimeStrToTime(this=datetime_literal)
5659    if isinstance(value, datetime.date):
5660        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5661        return DateStrToDate(this=date_literal)
5662    if isinstance(value, tuple):
5663        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5664    if isinstance(value, list):
5665        return Array(expressions=[convert(v, copy=copy) for v in value])
5666    if isinstance(value, dict):
5667        return Map(
5668            keys=[convert(k, copy=copy) for k in value],
5669            values=[convert(v, copy=copy) for v in value.values()],
5670        )
5671    raise ValueError(f"Cannot convert {value}")

Convert a python value into an expression object.

Raises an error if a conversion is not possible.

Arguments:
  • value: A python object.
  • copy: Whether or not to copy value (only applies to Expressions and collections).
Returns:

Expression: the equivalent expression object.

def replace_children( expression: sqlglot.expressions.Expression, fun: Callable, *args, **kwargs) -> None:
5674def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5675    """
5676    Replace children of an expression with the result of a lambda fun(child) -> exp.
5677    """
5678    for k, v in expression.args.items():
5679        is_list_arg = type(v) is list
5680
5681        child_nodes = v if is_list_arg else [v]
5682        new_child_nodes = []
5683
5684        for cn in child_nodes:
5685            if isinstance(cn, Expression):
5686                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5687                    new_child_nodes.append(child_node)
5688                    child_node.parent = expression
5689                    child_node.arg_key = k
5690            else:
5691                new_child_nodes.append(cn)
5692
5693        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)

Replace children of an expression with the result of a lambda fun(child) -> exp.

def column_table_names( expression: sqlglot.expressions.Expression, exclude: str = '') -> Set[str]:
5696def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5697    """
5698    Return all table names referenced through columns in an expression.
5699
5700    Example:
5701        >>> import sqlglot
5702        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5703        ['a', 'c']
5704
5705    Args:
5706        expression: expression to find table names.
5707        exclude: a table name to exclude
5708
5709    Returns:
5710        A list of unique names.
5711    """
5712    return {
5713        table
5714        for table in (column.table for column in expression.find_all(Column))
5715        if table and table != exclude
5716    }

Return all table names referenced through columns in an expression.

Example:
>>> import sqlglot
>>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
['a', 'c']
Arguments:
  • expression: expression to find table names.
  • exclude: a table name to exclude
Returns:

A list of unique names.

def table_name( table: sqlglot.expressions.Table | str, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None) -> str:
5719def table_name(table: Table | str, dialect: DialectType = None) -> str:
5720    """Get the full name of a table as a string.
5721
5722    Args:
5723        table: Table expression node or string.
5724        dialect: The dialect to generate the table name for.
5725
5726    Examples:
5727        >>> from sqlglot import exp, parse_one
5728        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5729        'a.b.c'
5730
5731    Returns:
5732        The table name.
5733    """
5734
5735    table = maybe_parse(table, into=Table)
5736
5737    if not table:
5738        raise ValueError(f"Cannot parse {table}")
5739
5740    return ".".join(
5741        part.sql(dialect=dialect) if not SAFE_IDENTIFIER_RE.match(part.name) else part.name
5742        for part in table.parts
5743    )

Get the full name of a table as a string.

Arguments:
  • table: Table expression node or string.
  • dialect: The dialect to generate the table name for.
Examples:
>>> from sqlglot import exp, parse_one
>>> table_name(parse_one("select * from a.b.c").find(exp.Table))
'a.b.c'
Returns:

The table name.

def replace_tables(expression: ~E, mapping: Dict[str, str], copy: bool = True) -> ~E:
5746def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5747    """Replace all tables in expression according to the mapping.
5748
5749    Args:
5750        expression: expression node to be transformed and replaced.
5751        mapping: mapping of table names.
5752        copy: whether or not to copy the expression.
5753
5754    Examples:
5755        >>> from sqlglot import exp, parse_one
5756        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5757        'SELECT * FROM c'
5758
5759    Returns:
5760        The mapped expression.
5761    """
5762
5763    def _replace_tables(node: Expression) -> Expression:
5764        if isinstance(node, Table):
5765            new_name = mapping.get(table_name(node))
5766            if new_name:
5767                return to_table(
5768                    new_name,
5769                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5770                )
5771        return node
5772
5773    return expression.transform(_replace_tables, copy=copy)

Replace all tables in expression according to the mapping.

Arguments:
  • expression: expression node to be transformed and replaced.
  • mapping: mapping of table names.
  • copy: whether or not to copy the expression.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders( expression: sqlglot.expressions.Expression, *args, **kwargs) -> sqlglot.expressions.Expression:
5776def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5777    """Replace placeholders in an expression.
5778
5779    Args:
5780        expression: expression node to be transformed and replaced.
5781        args: positional names that will substitute unnamed placeholders in the given order.
5782        kwargs: keyword arguments that will substitute named placeholders.
5783
5784    Examples:
5785        >>> from sqlglot import exp, parse_one
5786        >>> replace_placeholders(
5787        ...     parse_one("select * from :tbl where ? = ?"),
5788        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5789        ... ).sql()
5790        "SELECT * FROM foo WHERE str_col = 'b'"
5791
5792    Returns:
5793        The mapped expression.
5794    """
5795
5796    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5797        if isinstance(node, Placeholder):
5798            if node.name:
5799                new_name = kwargs.get(node.name)
5800                if new_name:
5801                    return convert(new_name)
5802            else:
5803                try:
5804                    return convert(next(args))
5805                except StopIteration:
5806                    pass
5807        return node
5808
5809    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression: expression node to be transformed and replaced.
  • args: positional names that will substitute unnamed placeholders in the given order.
  • kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_placeholders(
...     parse_one("select * from :tbl where ? = ?"),
...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
... ).sql()
"SELECT * FROM foo WHERE str_col = 'b'"
Returns:

The mapped expression.

def expand( expression: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy: bool = True) -> sqlglot.expressions.Expression:
5812def expand(
5813    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5814) -> Expression:
5815    """Transforms an expression by expanding all referenced sources into subqueries.
5816
5817    Examples:
5818        >>> from sqlglot import parse_one
5819        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5820        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5821
5822        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5823        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5824
5825    Args:
5826        expression: The expression to expand.
5827        sources: A dictionary of name to Subqueryables.
5828        copy: Whether or not to copy the expression during transformation. Defaults to True.
5829
5830    Returns:
5831        The transformed expression.
5832    """
5833
5834    def _expand(node: Expression):
5835        if isinstance(node, Table):
5836            name = table_name(node)
5837            source = sources.get(name)
5838            if source:
5839                subquery = source.subquery(node.alias or name)
5840                subquery.comments = [f"source: {name}"]
5841                return subquery.transform(_expand, copy=False)
5842        return node
5843
5844    return expression.transform(_expand, copy=copy)

Transforms an expression by expanding all referenced sources into subqueries.

Examples:
>>> from sqlglot import parse_one
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
Arguments:
  • expression: The expression to expand.
  • sources: A dictionary of name to Subqueryables.
  • copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:

The transformed expression.

def func( name: str, *args, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.Func:
5847def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5848    """
5849    Returns a Func expression.
5850
5851    Examples:
5852        >>> func("abs", 5).sql()
5853        'ABS(5)'
5854
5855        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5856        'CAST(5 AS DOUBLE)'
5857
5858    Args:
5859        name: the name of the function to build.
5860        args: the args used to instantiate the function of interest.
5861        dialect: the source dialect.
5862        kwargs: the kwargs used to instantiate the function of interest.
5863
5864    Note:
5865        The arguments `args` and `kwargs` are mutually exclusive.
5866
5867    Returns:
5868        An instance of the function of interest, or an anonymous function, if `name` doesn't
5869        correspond to an existing `sqlglot.expressions.Func` class.
5870    """
5871    if args and kwargs:
5872        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5873
5874    from sqlglot.dialects.dialect import Dialect
5875
5876    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5877    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5878
5879    parser = Dialect.get_or_raise(dialect)().parser()
5880    from_args_list = parser.FUNCTIONS.get(name.upper())
5881
5882    if from_args_list:
5883        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5884    else:
5885        kwargs = kwargs or {"expressions": converted}
5886        function = Anonymous(this=name, **kwargs)
5887
5888    for error_message in function.error_messages(converted):
5889        raise ValueError(error_message)
5890
5891    return function

Returns a Func expression.

Examples:
>>> func("abs", 5).sql()
'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
'CAST(5 AS DOUBLE)'
Arguments:
  • name: the name of the function to build.
  • args: the args used to instantiate the function of interest.
  • dialect: the source dialect.
  • kwargs: the kwargs used to instantiate the function of interest.
Note:

The arguments args and kwargs are mutually exclusive.

Returns:

An instance of the function of interest, or an anonymous function, if name doesn't correspond to an existing sqlglot.expressions.Func class.

def true() -> sqlglot.expressions.Boolean:
5894def true() -> Boolean:
5895    """
5896    Returns a true Boolean expression.
5897    """
5898    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
5901def false() -> Boolean:
5902    """
5903    Returns a false Boolean expression.
5904    """
5905    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
5908def null() -> Null:
5909    """
5910    Returns a Null expression.
5911    """
5912    return Null()

Returns a Null expression.

TRUE = (BOOLEAN this: True)
FALSE = (BOOLEAN this: False)
NULL = (NULL )